【发布时间】:2020-01-17 19:29:56
【问题描述】:
我的索引是这样的:
...
<html >
<head>
...
<script src="/scripts/myapp.min.js"></script>
<script src="/scripts/myapp-themming.min.js"></script>
</head>
<body class="header-static">
<div class="page-container">
<!-- this is call header, navigaton, content, footer -->
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/Content/assets/script/jquery-ui.min.js"></script>
...
<script type="text/javascript">
...
</script>
<script>
$(document).ready(function () {
...
});
</script>
</body>
</html>
如果我使用 gtmetrix 测试页面速度。和 gtmetrix 推荐延迟解析 JavaScript。所以我尝试像这样添加async:
<script src="/scripts/myapp.min.js" async></script>
<script src="/scripts/myapp-themming.min.js" async></script>
它显示以下错误,
未捕获的引用错误:$ 未定义
如果我使用 defer,它会产生 3 个这样的错误:Uncaught ReferenceError: $ is not defined、Uncaught TypeError: $(...).material_select is not a function 和 Uncaught TypeError: $(...).select2 is not a function
我该如何解决这个错误?
【问题讨论】:
-
看起来你在加载 jQuery 之前加载了你的 javascript - 如果你在 javascript 中使用 jQuery,你需要在加载 jquery 之后加载你的 javascript - 这就像在你上车之前尝试开车跨度>
-
@Jaromanda X 当我添加异步或延迟时会发生此错误。如果我不使用它,没有错误
-
@Jaromanda X 如果我在 jquery 脚本下移动标签脚本,它是一样的。还是有错误
-
如果包含依赖脚本B的脚本A,则需要确保脚本A运行时脚本B已满载。
async与此相反。 javascript.info/script-async-defer -
问题是
$()在 jquery 准备好之前运行。这就是 async 的用途,以防止脚本在并行下载时阻塞页面。这是您可以load and use jquery asynchronously的方法。
标签: javascript jquery asynchronous optimization pagespeed