Jquery - getScript vers. <script>..</script>
what is faster?
<script src="../js/SOME.js" type="text/javascript"></script>
OR
$.getScript('../j开发者_StackOverflow中文版s/SOME.js', function (){ ...
// with $.ajaxSetup({ cache: true });
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.
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.
The former, since $.getScript relies on jquery to be initialized.
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".
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>
精彩评论