What is the difference between this code
var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
and this code
<script type="text/javascript" src="http://your-script.com/address-here.js">
</script>
Thank you.
The javascript at the top is going to append a new element to the first head tag of the document that should equal out to
<script type="text/javascript" src="http://your-script.com/address-here"></script>(or close to). The only difference is that the browser will load the HTML version as soon as it comes across it whereas the JS won’t be loaded until the element is done being appended.As @lostsource mentions this would be typically used to load a dependency script or used to bring in polyfills, e.g.
if(!someJSFeatureIWant) {//import the script here}.