javascript 检测脚本是否已经加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13381821/
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
Detect if script has already loaded or not
提问by oshirowanen
It seems that helloworld.js
gets loaded multiple times based on the number of times I click #load
. I say this because when I look at Google Chromes Developer Tools Network tab, it shows helloworld.js
as many times as I click #load
.
似乎helloworld.js
根据我单击的次数加载了多次#load
。我这样说是因为当我查看 Google Chromes Developer Tools Network 选项卡时,它显示的helloworld.js
次数与我单击 的次数相同#load
。
$(document).ready(function() {
$("#load").click(function(){
$.getScript('helloworld.js', function() {
hello();
});
});
});
The hello()
function looks like this:
该hello()
函数如下所示:
function hello(){
alert("hello");
}
Is it possible to detect if helloworld.js
has already loaded?
是否可以检测是否helloworld.js
已经加载?
So if it hasn't loaded, load it, and if it has loaded, don't load it.
所以如果它没有加载,加载它,如果它已经加载,不要加载它。
This is what Developer Tools currently shows me if I click the #load
button 4 times:
如果我单击该#load
按钮 4 次,Developer Tools 当前显示的是:
采纳答案by Shadow Wizard is Ear For You
Another option is letting .getScript()
run but let it take the script from browser's cache so you won't have it reloaded each and every time.
另一种选择是让它.getScript()
运行,但让它从浏览器的缓存中获取脚本,这样你就不会每次都重新加载它。
To achieve this, add such code:
为此,请添加以下代码:
$.ajaxSetup({
cache: true
});
This is taken from the documentation page.
这是从文档页面中获取的。
回答by Muthu Kumaran
Set a flag when file loaded successfully. If flag is set then skip the file loading again.
文件加载成功时设置一个标志。如果设置了标志,则再次跳过文件加载。
Try this code,
试试这个代码,
var isLoaded = 0; //Set the flag OFF
$(document).ready(function() {
$("#load").click(function(){
if(isLoaded){ //If flag is ON then return false
alert("File already loaded");
return false;
}
$.getScript('helloworld.js', function() {
isLoaded = 1; //Turn ON the flag
hello();
});
});
});
回答by Gabe
So why not only fire the event once like this:
那么为什么不只像这样触发一次事件:
$("#load").one("click", function() {
$load = $(this);
$.getScript('helloworld.js', function() {
hello();
// bind hello to the click event of load for subsequent calls
$load.on('click', hello);
});
});
That would prevent subsequent loads and avoids the use of a global
这将防止后续加载并避免使用全局
回答by pimvdb
You could create a helper function:
您可以创建一个辅助函数:
var getScript = (function() {
var loadedFiles = {};
return function(filename, callback) {
if(loadedFiles[filename]) {
callback();
} else {
$.getScript(filename, function() {
loadedFiles[filename] = true;
callback();
});
}
};
})();