Reputation: 2310
Imagine the window is loaded. A 'click'
eventListener triggers the creation and appending of a 'dynamic script tag' (document.createElement(‘script’))
to the header (or somewhere else, I'm not sure if it matters).
Reading this article, it says dynamic tags start loading as soon as they're appended to the DOM. It also says they're async
by default - which means they're executed as soon as they're loaded.
I'm thinking, what we configure the dynamic tag to have no attribute or to have defer
? Can it have a different sort of behaviour? My guess is that, as there are no other scripts (because initial loading of .html
is completed) it'll have the same behaviour as async
(basically, executes as soon as it's loaded).
I'm aware of the behaviour of regular scripts and deferred scripts on 'initial execution of the .html
'. Now that we're not in this initial execution I feel a bit unconfident.
P.s. Is it strange/uncommon to have a dynamic tag created after initial execution of .html
i.e. from a click?
Upvotes: 1
Views: 88
Reputation: 4138
what [happens if] we configure the dynamic tag to have no attribute or defer?
Exactly as the article sais: it will have async
attribute by default.
This can be easily verified:
let script = document.createElement('script');
console.log(`async: ${script.async}`);
Can it have a different sort of behaviour?
For sure, just set attributes that you want:
let script = document.createElement('script');
script.async = true;
script.defer = true;
My guess is that, as there are no other scripts (because initial loading of .html is completed) it'll have the same behaviour as async (basically, executes as soon as it's loaded).
The exact behavior depends on how you load your other resources and in which order, as well as the browser implementation. But in general, yes, your assumption is correct.
Is it strange/uncommon to have a dynamic tag created after initial execution of .html i.e. from a click?
I would say that it's not very popular, but there's definitely nothing wrong with it. On the contrary, it's usually used to increase website performance. For example, if you're using a third-party library on your page (like YouTube) - you don't need it to be loaded unless the user clicks on the video. Then you can append the script and load the library.
Upvotes: 1