在JS文件中设置延迟以调用JS文件

Set a delay in a JS file to call upon a JS file

本文关键字:JS 文件 调用 延迟 设置      更新时间:2023-10-16

我试图让一个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);
});

在加载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文章。

此外,getElementsByTagName是一种糟糕的获取身体的方式。请改用document.body

这里有一个关于setTimeout:JSFiddle的简单演示。

您可以使用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
});