[英]Dynamic, cross-browser script loading
I know that IE doesn't have a load
event for <script>
elements — is there any way to make up for that reliably?我知道 IE 没有
<script>
元素的load
事件——有没有办法可靠地弥补这一点?
I've seen some talk of things (eg, requestState == "complete"
) but nothing very verifiable.我见过一些关于事情的讨论(例如
requestState == "complete"
),但没有什么非常可验证的。
This is to be used so that code can be called after a script is finished loading, so that I don't have to use AJAX to load new sources (thus eliminating issues with cross-domain AJAX).这是为了在脚本加载完成后调用代码,这样我就不必使用 AJAX 来加载新源(从而消除跨域 AJAX 的问题)。
You can use a script loader like head.js .您可以使用像head.js这样的脚本加载器。 It has its own load callback and it will decrease load time too.
它有自己的加载回调,它也会减少加载时间。
From the headjs
code: (slightly modified to be more portable)来自
headjs
代码:(稍作修改以更便携)
function scriptTag(src, callback) {
var s = document.createElement('script');
s.type = 'text/' + (src.type || 'javascript');
s.src = src.src || src;
s.async = false;
s.onreadystatechange = s.onload = function () {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
// use body if available. more safe in IE
(document.body || head).appendChild(s);
}
I want to add that if you don't support IE7 and below, you don't need onreadystatechange
stuff.我想补充一点,如果您不支持 IE7 及以下版本,则不需要
onreadystatechange
的东西。 Source: quircksmode.org资料来源: quirksmode.org
Simplified and working code from original answer:原始答案的简化和工作代码:
function loadScript(src, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.async = false;
if(callback) {
s.onload = callback;
}
document.body.appendChild(s);
}
This is just an extension of ilia's answer.这只是 ilia 答案的延伸。 I used scriptTag like this: Works great:
我像这样使用 scriptTag:效果很好:
// these 3 scripts load serially.
scriptTag(boot_config.DEPENDENCIES.jquery,function(){
// jquery ready - set a flag
scriptTag(boot_config.DEPENDENCIES.jqueryui,function(){
// jqueryui ready - set a flag
scriptTag(boot_config.DEPENDENCIES.your_app,function(){
// your_app is ready! - set a flag
});
});
});
// these 2 scripts load in paralell to the group above
scriptTag(boot_config.EXTERNALS.crypto,function(){
// crypto ready - set a flag
});
scriptTag(boot_config.EXTERNALS.cropper,function(){
// cropper ready - set a flag
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.