Add defer or async attribute to dynamically generated script tags via JavaScript

后端 未结 1 1938
感情败类
感情败类 2020-12-28 18:08

I am dynamically putting a script tag to the DOM of my page like this:

var tag = document.createElement(\'script\');
tag.src = \"https://www.youtube.com/ifra         


        
相关标签:
1条回答
  • 2020-12-28 18:38

    There's no need to add async to your script tag, since that attribute is enabled by default for dynamic scripts.

    As for defer, just as you change the src attribute in JavaScript, you can also enable that one like so:

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    tag.defer = true;
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    

    Alternatively, you can use setAttribute() for this.

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    tag.setAttribute('defer','');
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
    0 讨论(0)
提交回复
热议问题