Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay loading of script in dom by N seconds

After my site loaded, I want to delay the below javascript for 10 seconds

script:

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

i tried this but not working:

<script 
    setTimeout(
      function(){ 
        type="text/javascript" 
        id="io258wer15cfg789as69th07er64hziq" 
        src="//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq" 
        defer } 
    ,10000)>
</script>
like image 436
Alerts Avatar asked Nov 14 '25 20:11

Alerts


1 Answers

You need to add it using createElement. So that it will inject after 10s.

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);
}
like image 197
Kalpesh Singh Avatar answered Nov 17 '25 11:11

Kalpesh Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!