$ .getScript中未定义的函数 [英] Not defined function from $.getScript

查看:109
本文介绍了$ .getScript中未定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这必须非常简单.外部javascript文件包含:

This one must be very simple. An external javascript file contains:

function Hello() {
    alert('Hello');
}

它是getScript() ed,然后一个包含的函数被调用

It is getScript()ed and then a contained function is called

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $.getScript('myscript.js');
    Hello();
</script>

我得到:

ReferenceError:未定义Hello

ReferenceError: Hello is not defined

但是,如果脚本是在HTML <script>标记中引用的,它将按预期工作

But if the script is referenced in an HTML <script> tag it works as expected

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">
    Hello();
</script>

我缺少什么?如何引用在getScript() ed脚本中创建的对象?我想使用getScript()它在ready()事件上加载脚本的原因.

What I am missing? How to reference objects created in a getScript()ed script? The reason I want to use getScript() it to load the script on a ready() event.

推荐答案

问题是$.getScript()函数是异步的.此后立即调用Hello()函数时,脚本尚未加载,因此该函数不可用.

The issue is that the $.getScript() function is asynchronous. When you call the Hello() function immediately after, the script is not yet loaded so the function is not available.

使用常规<script>标记加载脚本是同步进行的,因此,如果要复制该行为,则必须在Ajax调用中禁用async选项.

Loading scripts with regular <script> tags happens synchronously, so if you want to duplicate that behavior you have to disable the async option in your Ajax call.

本身并不支持这一点,这样你就可以做到这一点使用<10>通话用适当的选项:

getScript alone does not support this, so you can do this using an $.ajax call with the appropriate options:

 $.ajax({
     url: 'myscript.js',
     dataType: 'script',
     async: false
});

这将阻止浏览器,直到脚本被加载.

This will block the browser until the script is loaded.

但是,更好的技术是使用$.getScript()支持的回调:

However, a better technique is to use a callback, which $.getScript() does support:

$.getScript('myscript.js', function() {
    Hello();
});

这篇关于$ .getScript中未定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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