在 onload() 之后加载外部 javascript 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21761954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load external javascript file after onload()
提问by Roman Tisch
I use this in the headtag:
我在head标签中使用它:
<script src="js/lightbox.js"></script>
Is it possible to remove this off the header and load this file with onload()?
是否可以将其从标题中删除并加载此文件onload()?
<body onload="...">...</body>
Note: This is not a function, it's an external js file with several functions.
注意:这不是一个函数,它是一个具有多个函数的外部 js 文件。
Thanks!
谢谢!
回答by Vinay Pratap Singh
<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.
我仍然认为最好在 jQuery 中加载并使用 $.getScript 代替,因为那里有很多好东西。
Can call this on body load
可以在身体负荷上调用这个
回答by AtanuCSE
回答by Fizk
If you want to do it without jQuery, use this
如果你想在没有 jQuery 的情况下做到这一点,请使用这个
function addScript(filename)
{
var scriptBlock=document.createElement('script')
scriptBlock.setAttribute("type","text/javascript")
scriptBlock.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(scriptBlock)
}
and call it with <body onload="addScript('myFile.js')". If you have multiple files to load, you could put in a wrapper, that adds all the files you want.
并用<body onload="addScript('myFile.js')". 如果您有多个文件要加载,您可以放入一个包装器,以添加您想要的所有文件。
回答by Mahesh
Use $(document).ready() and from this function load javascript. It sounds crazy but can be done. please follow http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
使用 $(document).ready() 并从此函数加载 javascript。这听起来很疯狂,但可以做到。请关注http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
回答by lshettyl
var JS = {
load: function(src, callback) {
var script = document.createElement('script'),
loaded;
script.setAttribute('src', src);
if (callback) {
script.onreadystatechange = script.onload = function() {
if (!loaded) {
callback();
}
loaded = true;
};
}
document.getElementsByTagName('head')[0].appendChild(script);
}
};
// Example with callback
JS.load("http://www.someawesomedomain.com/some.js", function() {
//Do your thing.
});

