我有一个 $(document).ready 函数(显示移动菜单),它必须等待 jQuery 导入。我注意到有时它会出现,有时它并不取决于 jQuery 是否先加载。 jQuery 导入是异步加载的。我想延迟 $(document).ready 函数,直到确定 jQuery 已经加载为止。我尝试使用 defer 和 async 但它似乎不起作用。我也尝试添加 setTimeout() 但它也不起作用。
<script async='async' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js' type='text/javascript' />
<script defer='defer' async='async' type='text/javascript'>
;(function ($, document, window) { var
// default settings object.
defaults = {
label: 'MENU',
duplicate: true,
duration: 200,
easingOpen: 'swing',
easingClose: 'swing',
closedSymbol: '►',
openedSymbol: '▼',
prependTo: 'body',
parentTag: 'a',
closeOnClick: false,
allowParentLinks: false,
nestedParentLinks: true,
showChildren: false,
init: function(){},
open: function(){},
close: function(){}
},... </script>
最佳答案
问题是您将 jQuery 作为异步加载:
<script async='async' <----------- this is the problem
src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'
type='text/javascript'
/>
async
属性告诉您的浏览器可以在执行页面上的所有其他 javascript 代码后加载此文件。解决方案是删除 async
.
但是不建议使用异步吗?
是的,但仅适用于页面上其他脚本不依赖的脚本。对于像 jQuery 这样的库,您需要确定已经加载,您不应该使用 async
.
但是如果浏览器等待 jQuery,会不会减慢页面加载速度?
是的,解决方案是将所有脚本标记移至页面底部 <head>
之外,就在 <body>
结束之前标签:
<html>
<head></head>
<body>
some stuff...
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js' type='text/javascript' />
<script type='text/javascript'>
;(function ($, document, window) { var
// default settings object.
defaults = {
label: 'MENU',
duplicate: true,
duration: 200,
easingOpen: 'swing',
easingClose: 'swing',
closedSymbol: '►',
openedSymbol: '▼',
prependTo: 'body',
parentTag: 'a',
closeOnClick: false,
allowParentLinks: false,
nestedParentLinks: true,
showChildren: false,
init: function(){},
open: function(){},
close: function(){}
},... </script>
</body>
</html>
但是我(或我的老板)不喜欢头脑之外的脚本!!
好吧,你仍然可以在头脑中编写你的脚本,但它有点复杂。基本上你需要监听 jquery 脚本标签的 onload 事件。但这意味着您需要动态创建标签,而不是在 html 中对其进行硬编码:
<html>
<head>
<script>
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js";
jq.async = true; // you can still load as async!
jq.onload = function () {
(function ($, document, window) { var
// default settings object.
defaults = {
label: 'MENU',
duplicate: true,
duration: 200,
easingOpen: 'swing',
easingClose: 'swing',
closedSymbol: '►',
openedSymbol: '▼',
prependTo: 'body',
parentTag: 'a',
closeOnClick: false,
allowParentLinks: false,
nestedParentLinks: true,
showChildren: false,
init: function(){},
open: function(){},
close: function(){}
},...
};
document.head.appendChild(jq);
</script>
</head>
<body> .... </body>
</html>
关于javascript - 如何让JS异步同时延迟脚本加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42288309/