将dom中的脚本加载延迟N秒

时间:2019-03-01 06:31:28

标签: javascript settimeout

网站加载后,我想将以下javascript延迟10秒钟

脚本:

<script type="text/javascript" id="io258wer15cfg789as69th07er64hziq" src="//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq" defer></script>

我尝试了此操作,但没有成功:

<script 
    setTimeout(
      function(){ 
        type="text/javascript" 
        id="io258wer15cfg789as69th07er64hziq" 
        src="//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq" 
        defer } 
    ,10000)>
</script>

2 个答案:

答案 0 :(得分:3)

您需要使用createElement添加它。这样它将在10秒后注入。

document.addEventListener("DOMContentLoaded", function(event) {
  setTimeout(addScript, 1000)
});

function addScript() {

  script = document.createElement('script');
  script.type = 'text/javascript';
  script.async = true;
  script.onload = function() {
    console.log("Added Script");
  };
  script.src = 'https://foo.com/bar.js';
  document.getElementsByTagName('head')[0].appendChild(script);
}

答案 1 :(得分:1)

尝试一下:

document.onload = function() {
  window.setTimeout(function () { 
    var script = document.createElement('script');
    script.async = true;
    script.id = 'io258wer15cfg789as69th07er64hziq';
    script.src = '//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq".src = "http://whatever.com/the/script.js';
    document.querySelector('head').appendChild(script);
  }, 10000);
};