I currently ran into a problem where a lazy loaded javascript would execute twice using internet explorer - and ONLY internet explorer (currently version 9). Firefox and chrome works. Here is my code:
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();
}
I already found this posting and changed my code according to it but still ie is executing my script twice. You guys got any ideas?
Edit: This is my solution
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();
}
Try this
s = document.createElement("script");
s.src="myscript.js";
if(s.addEventListener) {
s.addEventListener("load",callback,false);
}else if(s.readyState) {
s.onreadystatechange = callback;
}
document.body.appendChild(s);
function callback() { console.log("loaded"); }
taken from http://msdn.microsoft.com/en-us/library/ie/hh180173(v=vs.85).aspx
which for you would be...
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With