Peter
Peter

Reputation: 11835

Jquery - getScript vers. <script>..</script>

what is faster?

<script src="../js/SOME.js" type="text/javascript"></script>

OR

   $.getScript('../js/SOME.js', function (){ ... 
   // with $.ajaxSetup({ cache: true }); 

Upvotes: 1

Views: 1343

Answers (5)

mcbeav
mcbeav

Reputation: 12275

The fastest would be to load the scripts synchronously whith a script like:

<script id="your-script-id" type="text/javascript">

(function() {
 var your-script-id = document.createElement('script');
 your-script-id.type = 'text/javascript';
 your-script-id.src = ('http://your-script-location.js');
 var s = document.getElementById('your-script-id');
 s.parentNode.insertBefore(your-script-id, s);
})();

</script>

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

They will both take approximately the same time to download. The difference is that the inline script loads with all the rest of the elements on the page, and therefore must compete for bandwidth.

Injecting the script will take place after the page had loaded and after jQuery has loaded. Since the rest of the page elements are likely downloaded by this time it will seem "faster" but will be ready to use "later".

Upvotes: 1

Blender
Blender

Reputation: 298392

I'd guess that <script src="../js/SOME.js" type="text/javascript"></script> is faster, as the browser does it natively, while the second alternative first forces the browser to load the page, then use JavaScript to load the script.

The browser might take care of caching by itself, but I'm not too certain.

Upvotes: 3

amosrivera
amosrivera

Reputation: 26524

They are the same. But this are facts you should take into account:

  • To use getScript you need to have loaded jQuery first so add that time (i'm guessing that is what you are using becuase of the $).

  • jQuery would load it asynchronously which means the browser won't stop everything else to load SOME.js.

Upvotes: 3

John Giotta
John Giotta

Reputation: 16964

The former, since $.getScript relies on jquery to be initialized.

Upvotes: 1

Related Questions