加载页面后推迟javascript和jquery的终极解决方案 [英] Ultimate solution to defer javascript and jquery after page is loaded
问题描述
您可能知道, Google PageSpeed Insights 希望您推迟使用javascript。
As you probably know, Google PageSpeed Insights wants you to defer your javascript.
Google本身建议解决方案推迟您的代码:
Google itself suggests a solution to defer your code:
<script type="text/javascript">
function downloadJSAtOnload()
{
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
当然是一个很好的解决方案,但它远非真实的情况(包括许多脚本,代码执行等...)
Of course is a good solution, but it's far from the real circumstances (many scripts to include, code to execute, etc...)
从一个例子开始说明:
<html>
<head>
</head>
<body>
<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'><!--
// some code
$(document).ready(function(){
// code to execute when the page is ready
});
--></script>
</body>
</html>
问题是:如何将Google建议应用于上述示例?
The question is: How to apply the Google suggestion to the example above?
推荐答案
如果你有 downloadJSatOnload
附加几个脚本元素,Google示例可以用于多个脚本页面,然后调用通常放在 $(document).ready(function(){...});
中的代码。该代码可以显式调用,也可以是下载的最后一个文件。
The Google example can work for multiple scripts if you have the downloadJSatOnload
append several script elements to the page, and then call the code you would normally put in $(document).ready(function () { ... });
. That code could be called explicitly or be the last file downloaded.
这篇关于加载页面后推迟javascript和jquery的终极解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!