Why call $ .getScript instead of the direct <script> tag?

I do not understand the reason for replacing this:

<script src="js/example.js"></script>

with this:

$.getScript('js/example.js', function() {
  alert('Load was performed.');
});

Is there a specific reason to use the jQuery version?

+5
source share
5 answers

The only reason I can think of is to get a callback when loading the script. But you can get this callback using a tag script, also using an event load(or in a really old IE, onreadystatechange).

On the contrary, there are several negatives that do it this way, not least that getScriptobeys the same policy of origin , while a scriptdoes not.

script ( , ), , , , script script:

$('head:first').append("<script type='text/javascript' src='js/examplejs'><\/script>");

(: \, script, , script.)

script , , . load, :

$("<script type='text/javascript' src='js/examplejs'><\/script>")
    .on("load", function() {
        // loaded
    })
    .appendTo('head:first');

( , IE , .)

+7

, jQuery:

  • , script , , script , . . jQuery script , , <script> , .
  • <script> , HTML; , script, <script>, script, , JavaScript, jQuery.
  • jQuery script .
+6

.

, script ( , )

0

script jQuery, , jQuery.

There are a number of reasons why jQuery may not load, from a simple network failure to a CDN being marked with a NoScript user symbol .

0
source

perhaps to control when the script loads? On a heavy page, javascript might be worth waiting for some things to load that aren't significant until the necessary things load.

0
source

All Articles