问题
I want to programmatically load a .js file and do some stuff when it's finished loading. The file I want to include is hosted on the domain where it will be included.
Specifically, the file I'm loading is swfobject.js. I want to check for its existence and load it only if needed.
Here's what I have so far:
// BHD is defined elsewhere. For this example:
var BHD = {};
BHD.uid = function () {
return 'x'+(+(''+Math.random()).substring(2)).toString(32)+(+new Date()).toString(32);
};
BHD.include = function (file, callback) {
var uid = BHD.uid();
frame = document.createElement('iframe');
frame.src = file;
frame.id = frame.name = uid;
frame.onload = function () {
var s = document.getElementsByTagName('script')[0];
var d = frames[uid].document.documentElement;
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = d.textContent||d.innerText;
s.parentNode.insertBefore(script, s);
callback();
s.parentNode.removeChild(s);
frame.parentNode.removeChild(frame);
}
document.documentElement.appendChild(frame);
}
This seems to work. It's an ugly hack, though. The contents of the .js file is loaded in an iframe, and when the iframe is finished loading, a new script element is injected into the main document with the contents of the iframe. This seems to make the script load immediately, so the callback can be called immediately afterward.
I am wondering if there is a better way to do this. I'm looking for something along the lines of a cross-browser 'onload' event for script tags, or some other way to avoid the iframe hack.
回答1:
Modern versions of IE support the load
event on script elements (and readystate
is no longer supported), so the usual load
event techniques will work, multiple code paths are not required, and we no longer need to put up with the bug-ridden readystate.
来源:https://stackoverflow.com/questions/8631548/cross-browser-javascript-loading-with-callback-is-there-a-better-way-than-using