问题
I've got a jQuery plugin I made which will nicely format dates on elements with certain attributes on them. Overall it works, but I'm having some problems with Modernizr, but ONLY in IE and ONLY after a form postback.
Here's a snippet from the plugin where it uses the fantastic MomentJS library. Basically the first time the plugin is called, it will download the needed file then run the code to parse dates. If it is called any time afterwards and the library has already been downloaded, it can just go ahead and run the date parsing code.
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);
});
}
}
When I do this in IE9 only after a page postback, I get an error within the setupDisplayDate
function saying that moment is not defined. What am I doing wrong?
I did find that if I do a timeout of 500ms it will work, but I shouldn't have to do that. I thought the whole point of the Modernizr.load
feature was to download the code, and then make it available. It seems to download it and the fire my callback before it is available to use.
EDIT
Here's [a blog post about how IE9 will not properly dynamically added scripts: http://www.guypo.com/technical/ies-premature-execution-problem/
Any way around this?
Another Edit
It seems like the issues is actually regarding multiple calls to the load
function and then the various callbacks firing out of order. There's an open issue on GitHub about it and this reproducible test case.
来源:https://stackoverflow.com/questions/16150762/modernizr-download-file-but-it-is-still-undefined-afterwards-only-in-ie9-afte