$ .getScript中未定义的函数

编程入门 行业动态 更新时间:2024-10-20 21:09:24
本文介绍了$ .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="ajax.googleapis/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="ajax.googleapis/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.

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

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中未定义的函数

本文发布于:2023-11-28 06:59:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641384.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   中未   定义   getScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!