Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - Why call $.getScript instead of using the <script> tag directly?

I don't 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 particular reason to use the jQuery version?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only reason I can think of is that you get the callback when the script is loaded. But you can get that callback using a script tag, too, by using the load event (or on really old IE, onreadystatechange).

In contrast, there are several negatives to doing it this way, not least that getScript is subject to the Same Origin Policy, whereas a script tag is not.

Even if you need to load a script dynamically (and there are several reasons you might need to do that), frankly unless you really need the callback, I'd say you're better off just loading the script by adding a script tag:

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

(Note: You need the otherwise-unnecessary in the ending tag in the above to avoid prematurely ending the script tag this code exists within, if it's in an inline script tag.)

script tags added in this way are not subject to the Same Origin Policy. If you want the load callback, then:

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

(As I said, for really old IE, you'd have to do more than that, but you shouldn't need to deal with them these days.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...