我想以异步/延期模式调用JavaScript文件,因为这是一个很好的做法。但是,当我尝试使用jQuery/jquery-ui JS同样的事情时,它不再起作用了?
我的代码有什么问题吗?如果是这样,请纠正我。
<html>
<head>
<title>Dashboard</title>
<!--script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" async></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript" async></script-->
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript" async></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" type="text/javascript" async></script>
</head>
<body>
<div id="demo" style="border: 1px solid black; width:400px; height:300px;" class="ui-widget-content">
<p>Hello Dragger</p>
</div>
<script>
$(document).ready(function () {
$("#demo").draggable();
});
</script>
</body>
我得到了例外" (索引):15未介绍的参考:$未定义(…)",因为我正在使用异步/defer的东西。但是我已经在使用文档。已经准备好摆脱此例外。
它只能使用Settimeout运行,但不是更清洁的方法。请帮助我。
谢谢
我想更快地加载DOM,因此我使用了异步/defer。但是$ jquery变量没有定义,因为jQuery库尚未加载。因此,为了处理此操作,我只需将我的jQuery代码插入窗口
window.onload = function () {
$(function () {$("#demo").draggable();
});
}
<html>
<head>
<title>Dashboard</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript" async></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" type="text/javascript" async></script>
</head>
<body>
<div id="demo" style="border: 1px solid black; width:400px; height:100px;">
<p>Hello Dragger</p>
</div>
<script src="../static/js/external.js" type="text/javascript" async></script>
</body>
</html>
我希望这可能会帮助别人(新手像我一样)。
这里的问题是,您是异步加载脚本的。因此,脚本需要一些时间才能加载到网页中(也许很小的英里秒)。
在此之前将调用$(document).ready
,但当时jQuery脚本未加载。
要处理这种情况,您可以使用任何模块加载程序,例如requirejs,这是jQuery-ui已经支持的AMD模块加载器。
<html>
<head>
<title>Dashboard</title>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>-->
<!--<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript" defer></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" type="text/javascript" defer></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.2/require.min.js"></script>
</head>
<body>
<div id="demo" style="border: 1px solid black; width:400px; height:300px;" class="ui-widget-content">
<p>Hello Dragger</p>
</div>
<script>
requirejs.config({
paths: {
"jquery": "https://code.jquery.com/jquery-1.12.4",
"jquery-ui": "https://code.jquery.com/ui/1.12.1/jquery-ui"
}
});
require(["jquery-ui"], function () {
$("#demo").draggable();
});
</script>
</body>