我目前遇到了一个问题,即延迟加载的 javascript 将使用 Internet Explorer 执行两次 - 并且仅 Internet Explorer(当前版本 9)。火狐和铬的作品。这是我的代码:
injectExternalJavaScript: function(fileUrl) {
return jQuery.Deferred(function(deferred) {
var script = document.createElement('script');
script['src'] = fileUrl;
script['type'] = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
var done = false;
// Attach handlers for all browsers
script['onload'] = script['onreadystatechange'] = function() {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === 'complete')) {
done = true;
script['onload'] = script['onreadystatechange'] = null;
head.removeChild(script);
deferred.resolve();
}
};
head.appendChild(script);
}).promise();
}
我已经找到了这个帖子并根据它更改了我的代码,但仍然执行我的脚本两次。你们有什么想法吗?
编辑:这是我的解决方案
injectExternalJavaScript: function(fileUrl) {
return jQuery.Deferred(function(deferred) {
var script = document.createElement('script');
script['src'] = fileUrl;
script['type'] = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
var done = false;
// Attach handlers for all browsers
var cb = function() {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === 'complete')) {
done = true;
script['onload'] = script['onreadystatechange'] = null;
head.removeChild(script);
deferred.resolve();
}
}
if (script.addEventListener) {
script.addEventListener('load', cb, false);
} else {
script['onreadystatechange'] = cb;
}
head.appendChild(script);
}).promise();
}