您可能知道,Google PageSpeed Insights希望您推迟 javascript。
Google 本身提出了一种延迟代码的解决方案:
<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>
当然是一个很好的解决方案,但它与实际情况相去甚远(要包含许多脚本,要执行的代码等......)
举个例子:
<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>
问题是:如何将谷歌的建议应用到上面的例子中?