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

I dynamically put the script tag in the DOM of my page as follows:

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

This should generate something like this:

<script src="https://www.youtube.com/iframe_api"></script>

I just want to add or disable this script tag as follows:

<script src="https://www.youtube.com/iframe_api" defer async></script>

So how do I do this with javascript?

+8
source share
2 answers

There is no need to add asyncto the tag script, since this attribute is enabled by default , and scripts will be loaded asynchronously if not said.

As for defer, just as you change an attribute srcin JavaScript, you can also include it like this:

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);

setAttribute() .

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);
+26

( ), .

<!DOCTYPE html>
<html>
  <head>
    <script src="https://andreymakahov.imtqy.com/defer/big.js" crossorigin="anonymous" defer></script>
  </head>
  <body>
    <script>
      var script = document.createElement('script');
      script.src ="https://andreymakahov.imtqy.com/defer/small.js";
      script.defer = true;
      document.body.appendChild(script);
    </script>
  </body>
</html>

, :

  1. big.js , , console.log('big'). .
  2. small.js console.log('small').

, HTML, :

  1. big.js
  2. small.js

:

> small
> big

, , , big.js .

, , ?

-1

Source: https://habr.com/ru/post/1664597/


All Articles