[英]How to run a Javascript function after a specific JS has loaded?
I have made a js function for including another Javascript in my html.我制作了一个 js 函数,用于在我的 html 中包含另一个 Javascript。 I need to make sure that the script I have loaded using the function is has completed processing and then only move further in my original script.我需要确保使用该函数加载的脚本已完成处理,然后仅在我的原始脚本中进一步移动。
function loadBackupScript(){
var script = document.createElement('script');
script.src = 'http://www.geoplugin.net/javascript.gp';
script.type = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}
I need to know that the script has loaded to use its functions ahead.我需要知道脚本已加载以使用其功能。 How do I do that?我怎么做?
function loadBackupScript(callback) {
var script;
if (typeof callback !== 'function') {
throw new Error('Not a valid callback');
}
script = document.createElement('script');
script.onload = callback;
script.src = 'http://www.geoplugin.net/javascript.gp';
document.head.appendChild(script);
}
loadBackupScript(function() { alert('loaded'); });
Add this to your function:将此添加到您的函数中:
// all cool browsers
script.onload = doSomething;
// IE 6 & 7
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
doSomething();
}
IF you don't trust these events you could also use setTimeout() to check for the existence of the function.如果您不信任这些事件,您还可以使用 setTimeout() 来检查该函数是否存在。 A good article on this can be found here:可以在这里找到一篇关于此的好文章:
http://www.ejeliot.com/blog/109 http://www.ejeliot.com/blog/109
I would recommend using LABJs for this.我建议为此使用LABJ 。
Using it you can do this使用它你可以做到这一点
$LAB
.script("framework.js")
.wait(function(){
//called when framework.js is loaded
})
.script("init.js")
.wait(function(){
//called when init.js is loaded
});
This is cross-browser and will often be more efficient than hardcoding script tags into your html due to the way it supports parallel downloads.这是跨浏览器的,由于它支持并行下载的方式,因此通常比将脚本标签硬编码到 html 中更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.