我正在尝试将另一个Javascript文件加载,但我想在延迟后加载第二个文件。我需要添加什么才能延迟?
$(document).ready(function() {
var script = document.createElement('script');
script.src = "https://lib.store.yahoo.net/lib/yhst-136932942155053/BongoCheckout.Yahoo.2.js";
document.getElementsByTagName('body')[0].appendChild(script);
});
答案 0 :(得分:1)
您可以使用window.setTimeout(func, millisecs)
$(document).ready(function() {
var script = document.createElement('script');
script.src = "https://lib.store.yahoo.net/lib/yhst-136932942155053/BongoCheckout.Yahoo.2.js";
window.setTimeout(function () {
document.getElementsByTagName('body')[0].appendChild(script);
}, 1000); // 1 sec
});
答案 1 :(得分:0)
在加载Javascript文件之前,您可以使用setTimeout
延迟X毫秒。
$(document).ready(function() {
var script = document.createElement('script');
script.src = "https://lib.store.yahoo.net/lib/yhst-136932942155053/BongoCheckout.Yahoo.2.js";
setTimeout(function(){
document.body.appendChild(script);
},2000); // 2000 is the delay in milliseconds
});
setTimeout
将在几毫秒后运行您提供的函数。
有关setTimeout
的更多官方资料,请参阅此MDN Article。
此外,getElementsByTagName
是获取身体的糟糕方式。请改用document.body
。
以下是setTimeout
上的简单演示:JSFiddle。