onload()后加载外部JavaScript文件 [英] Load external javascript file after onload()

查看:90
本文介绍了onload()后加载外部JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标记中使用它:

 < script src =js / lightbox.js>< / script> 

是否可以从标题中删除它,并使用 onload加载此文件()

 < body onload =...> ...< ; /体> 

注意:这不是一个函数,它是一个包含多个函数的外部js文件。


$ b

谢谢!

解决方案

 < script> ; 
函数loadJS(src,callback){
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function(){
var state = s.readyState;
if(!callback.done&&(!state || /loadedcombilled/.test(state))){
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0] .appendChild(s);
}
loadJS('/ script / script.js',function(){
//将脚本加载后运行你的代码
});
< / script>

我仍然认为在jQuery中加载并使用$ .getScript会更好,因为您有很多好东西在那里。



可以在身体负荷上调用此功能

I use this in the head tag:

<script src="js/lightbox.js"></script>

Is it possible to remove this off the header and load this file with onload()?

<body onload="...">...</body>

Note: This is not a function, it's an external js file with several functions.

Thanks!

解决方案

<script>
function loadJS(src, callback) {
    var s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onreadystatechange = s.onload = function() {
        var state = s.readyState;
        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('/script/script.js', function() { 
    // put your code here to run after script is loaded
});
</script>

I still think its better to load in jQuery and use $.getScript instead as you have lots of goodies there.

Can call this on body load

这篇关于onload()后加载外部JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆