40

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/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 put in a defer or async to this script tag like this:

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

So how do I do this using JavaScript?

3 Answers 3

96

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);
Sign up to request clarification or add additional context in comments.

5 Comments

How about tag.defer = true?
The link article on MDN does not say anything about async being the default for dynamic script tags. Can you reference exactly where it does say so?
Dynamic scripts are created with async flag enabled by default.
I was able to set defer attribute for dynamic scripts, but couldn't find any difference with it's presence. Can I please know if it will have any effect ?, I mean does it behave like a static script with defer attribute?
Dynamically inserted scripts are ALWAYS async, defer attribute will be ignored. Please see my answer.
2

In order to load dynamic scripts asynchronously, but execute them in the order of definition, use script.async = false:

['1.js', '2.js'].forEach(s => {
   const script = document.head.appendChild(document.createElement('script'));
   script.async = false;
   script.src = s;
});

Source: https://web.dev/speed-script-loading/#the-dom-to-the-rescue

Comments

1

The defer attribute is ignored for dynamically inserted scripts. They will always be loaded async. You can read more about it here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.