JavaScript-需要加载外部JS文件的功能 [英] JavaScript - function to load external JS files is needed
问题描述
最近,我将按钮之类的Facebook添加到了我的网站,Twitter跟随了我们,Twitter以及了Google +1按钮.当我告诉他们加载我的JS脚本时.
Recently I added to my website facebook like button, twitter follow us button and google +1 button. I want their JS scripts to load when I tell them to load.
因此,我需要一个加载外部JS文件的函数.我不需要知道文件何时完成加载(不需要回调).
Therefore, I need a function that load external JS files. I don't need to know when the file finished to load (callback is not needed).
我在Internet上找到了一些方法/功能,但是我想知道哪种方法/功能最适合这种情况?
I found some methods/functions on the Internet, but I want to know which would be the best choice for this situation?
4种动态方法加载外部JavaScript
动态加载JS库并检测何时加载
加载外部文件的最佳方法JavaScript
4 ways to dynamically load external JavaScript
Dynamically loading JS libraries and detecting when they're loaded
The best way to load external JavaScript
谢谢.
修改: 添加了我发现的方法/功能.
Edit: Added the methods/function I found.
推荐答案
这可能会有所帮助:
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
这篇关于JavaScript-需要加载外部JS文件的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!