Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script src javascript

Tags:

javascript

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.

like image 240
user1801625 Avatar asked Jul 15 '26 01:07

user1801625


2 Answers

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}.

like image 58
Snuffleupagus Avatar answered Jul 16 '26 13:07

Snuffleupagus


The first one is normally used as a way to include additional Javascript files required by a Script. (it is just dynamically creating a <script> tag like the second code sample)

For example you might include the core functionality in a main.js file, then depending on user interactivity you decide to include other scripts. (eg. graphics.js, forms.js etc..)

The same approach is also used to make JSON-P requests by dynamically including a url which returns a JSON 'padded' response. With the main advantage over iframes and regular XHR requests being that <script> tags are not affected by the same origin policy.

like image 29
lostsource Avatar answered Jul 16 '26 14:07

lostsource



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!