javascript 来自 $.getScript 的未定义函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19716310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:34:48  来源:igfitidea点击:

Not defined function from $.getScript

javascriptjquery

提问by Clodoaldo Neto

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

这个一定很简单。外部 javascript 文件包含:

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

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

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

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

I get:

我得到:

ReferenceError: Hello is not defined

参考错误:Hello 未定义

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

但是如果脚本在 HTML<script>标签中被引用,它会按预期工作

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

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()ed 脚本中创建的对象?我想用getScript()它来加载ready()事件脚本的原因。

回答by nullability

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.

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

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

加载带有常规<script>标签的脚本是同步发生的,因此如果您想复制该行为,您必须async在 Ajax 调用中禁用该选项。

getScriptalone does not support this, so you can do this using an $.ajaxcall with the appropriate options:

getScriptalone does not support this, so you can do this using an $.ajaxcall with the appropriate options:

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

This will block the browser until the script is loaded.

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

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

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

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

回答by Madbreaks

You need to wait for the response:

您需要等待响应:

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