Reputation: 10878
Is there any advantages of loading a script using HTMLScriptElement instead of loading it by just including it in the DOM?
Maybe for instance it would be easier to keep things clean in the DOM and also hide the scripts (make them less obvious)?
Didn't find any sources on this, that's why I am asking.
Upvotes: 4
Views: 1929
Reputation: 1849
Normally, you would just include script tags directly in the HTML document. Unless you use the async
attribute, subsequent scripts will won't load until the previous ones so you can safely rely on any dependencies to be available.
You could use the HTMLScriptElement
interface programmatically to load scripts, if you wanted to keep your HTML cleaner. However, then you'd have to manually create onload
and onerror
handlers to asynchronously wait for the script(s) to load. This would get messy and complicated unless you build an abstraction around it. And then you're doing something done many times before, see RequireJS, SystemJS et al.
So, wanting to keep your HTML clean of script tags is a reasonable ambition, but you're probably best off looking into an off-the-shelf script loader to do that rather than rolling your own.
Upvotes: 1
Reputation: 17430
There is not really a choice here. HTMLScriptElement
is the "interface" exposed by all HTML <script>
nodes.
One creates script nodes by calling document.createElement('script')
or by passing a <script>...</script>
tag string through the HTML parser (this can happen in a variety of ways: from parsing a complete HTML document to setting the innerHTML
of an existing element.) When a <script>
element is created in an HTML document, HTMLScriptElement
is in its prototype chain. Therefore, all properties and methods on HTMLScriptElement
are accessible to the <script>
element.
HTMLScriptElement
is not a constructor function, however. This can be seen by attempting to invoke new HTMLScriptElement()
, which throws an Illegal constructor
TypeError
.
All this is to say that your question does not really make sense, since one cannot load "a script using HTMLScriptElement instead of loading it by just including it in the DOM".
Upvotes: 1