我有一个jQuery插件,它可以很好地格式化具有某些属性的元素的日期。总体而言,它有效,但我在使用Modernizr时遇到了一些问题,但仅限于IE浏览器,并且仅在表单回发后出现。
这是插件的一个片段,它使用了很棒的MomentJS library。基本上第一次调用插件时,它会下载所需的文件,然后运行代码来解析日期。如果在之后的任何时间调用它并且已经下载了库,它可以继续运行日期解析代码。
function parseDates() {
var $items = this;
if (typeof moment !== "undefined") {
//If we are calling this at a time after page load, just run the function
setupDisplayDate();
} else {
//If the files have not been included yet, download them & call the function
//Load in a date library!
Modernizr.load({
load: SCRIPTS_PATH + "moment.min.js",
callback: setupDisplayDate
});
}
function setupDisplayDate() {
console.log("setupDisplayDate called! Moment is " + typeof moment);
$items.each(function () {
var $thisItem = $(this);
var formatter = $thisItem.data("date-format") || "MMMM Do, YYYY";
var ticks = parseInt($thisItem.data("date-ticks"), 10);
var formattedDate = moment(ticks).format(formatter);
$thisItem.text(formattedDate);
});
}
}
当我在IE9中仅在页面回发后执行此操作时,我在setupDisplayDate
函数中收到一条错误,指出该时刻未定义。我究竟做错了什么?
我确实发现,如果我超时500毫秒它会起作用,但我不应该这样做。我认为Modernizr.load
功能的重点是下载代码,然后使其可用。它似乎可以下载它,并在它可以使用之前点燃我的回调。
这是[关于IE9如何不能正确动态添加脚本的博客文章:http://www.guypo.com/technical/ies-premature-execution-problem/
有什么方法吗?
似乎问题实际上涉及对load
函数的多次调用,然后是各种不按顺序触发的回调。关于它和open issue on GitHub有一个this reproducible test case。