Reputation: 11225
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?
Upvotes: 40
Views: 56293
Reputation: 2586
The defer attribute is ignored for dynamically inserted scripts. They will always be loaded async. You can read more about it here.
Upvotes: 1
Reputation: 75
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
Upvotes: 2
Reputation: 18659
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);
Upvotes: 96