我在一个网站上工作并致力于其 Page Speed Insights 并且有一个
Eliminate render-blocking JavaScript and CSS in above-the-fold content
所以基本上发生的事情是我在页面顶部有两个外部 javascript 导入:
<script src="/remotestaff_2015/js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="/remotestaff_2015/js/bootstrap.min.js" type="text/javascript"></script>
该网站有很多 javascript,但有些位于页面底部 <body>
之后标签。所以我的问题是上面的那两个。为了修复我已经在谷歌上搜索过的渲染 block ,发现我可以使用 defer
或 async
属性。我的问题是网站上有一些模块具有内联 javascript,例如:
<script type="text/javascript">
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
if ($("#wrapper").hasClass("toggled")) {
$(".color-fade").css("opacity", ".5");
} else {
$(".color-fade").css("opacity", "1");
}
});
所以如果我延迟我的 jquery
文件 我的内联 javascripts 会出错,因为它会在没有加载 jquery 的情况下加载。有没有办法修复此内联脚本或以某种方式使它们在加载延迟的 jquery 或其他 js 文件后运行?我不想将那些内联脚本放在其他文件中。
最佳答案
根据 MDN:
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
因此,让您的内联脚本等待文档和延迟脚本的加载。 DOMContentLoaded
事件将在发生时触发:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Inline scripts go here
});
</script>
请注意,不再需要 $(document).ready(function()
,因为它会等待相同的事件 (DOMContentLoaded
)。
关于javascript - 加载内联 jQuery 脚本以及延迟和异步脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606047/