为什么要调用$ .getScript而不是使用< script>直接标记? [英] Why call $.getScript instead of using the <script> tag directly?

查看:106
本文介绍了为什么要调用$ .getScript而不是使用< script>直接标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白更换此内容的原因:

I don't understand the reason for replacing this:

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

这个:

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

有没有特别的理由使用jQuery版本?

Is there a particular reason to use the jQuery version?

推荐答案

我能想到的唯一原因是你在加载脚本时得到了回调。但是,您也可以使用加载事件(或者在真正的旧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.)

这篇关于为什么要调用$ .getScript而不是使用&lt; script&gt;直接标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆