且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要调用$ .getScript而不是使用< script>直接标记?

更新时间:2023-09-29 22:11:04

我能想到的唯一原因是你在加载脚本时得到了回调。但是,您也可以使用加载事件(或者在真正的旧IE上)使用脚本标记来获取回调, onreadystatechange )。

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

相比之下,有几个否定这样做方式,尤其是 getScript 同源策略,而脚本标记不是。

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.

即使您需要动态加载脚本(并且有几个原因你可能需要这样做),坦率地说,除非你真的需要回调,否则我会说你***通过添加脚本加载脚本 tag:

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 以这种方式添加的标签 not 受同源策略的约束。如果你想要加载回调,那么:

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');

(正如我所说,对于真正老的IE,你必须做的不仅仅是这个,但是这些天你不需要处理它们。)

(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.)