gpt4 book ai didi

javascript - 延迟解析 JavaScript 以加载 JQuery

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:51:57 26 4
gpt4 key购买 nike

在使用 Google Page Speed 测试网站时,我发现无法摆脱 Defer parsing of JavaScript。我删除了所有 javascript 代码,只留下一小部分作为

<script defer type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function(){
$(this).slideDown();
});
});
</script>

或者甚至没有任何 jQuery 代码,只加载独立的 jQuery 文件作为

<script defer type="text/javascript" src="jquery.min.js"></script>

仍然收到关于 Defer parsing of JavaScript 的警告。

最佳答案

我找到了 this documentation page ,即:

To use this technique, you should first identify all of the JavaScript functions that are not actually used by the document before the onload event. For any file containing more than 25 uncalled functions, move all of those functions to a separate, external JS file. This may require some refactoring of your code to work around dependencies between files. (For files containing fewer than 25 uncalled functions, it's not worth the effort of refactoring.)

Then, you insert a JavaScript event listener in the head of the containing document that forces the external file to be loaded after the onload event. You can do this by any of the usual scripting means, but we recommend a very simple scripted DOM element (to avoid cross-browser and same-domain policy issues). Here's an example (where "deferredfunctions.js" contains the functions to be lazily loaded)

我从中了解到:您应该从 onload 事件处理程序“延迟加载”jQuery(有关如何执行此操作的示例,请参见上面的链接)。

关于javascript - 延迟解析 JavaScript 以加载 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com