跨浏览器的JavaScript加载有回调:是否有比使用内部框架更好的办法? [英] Cross-browser javascript loading with callback: Is there a better way than using iframes?
问题描述
我想以编程方式加载.js文件,当它完成加载做一些东西。该文件我想包括托管在那里将被列入域。
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.
具体来说,我加载该文件swfobject.js。我要检查它的存在,并仅在需要时加载它。
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);
}
这似乎工作。这是一个丑陋的黑客攻击,虽然。该.js文件的内容加载在iframe,当的iframe装载完毕,一个新的脚本元素注入的iframe的内容主要文件。这似乎立即使脚本负载,因此回调可随即调用。
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.
我想知道是否有更好的方法来做到这一点。我在寻找沿脚本标记一个跨浏览器的onload事件,或者一些其他的方式,以避免黑客的iframe的东西线。
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.
推荐答案
IE浏览器的现代版本支持负荷
事件的脚本元素(及的readyState
不再支持),所以平时负荷
事件技术将正常工作,并不需要多个code路径,我们不再需要忍受的<一个href=\"http://jebaird.com/2010/04/09/internet-explorer-bug-readystate-on-empty-cache-slow-to-complete.html\"相对=nofollow>错误缠身 <一个href=\"https://connect.microsoft.com/IE/feedback/details/729164/ie10-dynamic-script-element-fires-loaded-readystate-$p$pmaturely\"相对=nofollow> readyState的。
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.
这篇关于跨浏览器的JavaScript加载有回调:是否有比使用内部框架更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!