问题
As you probably know, Google PageSpeed Insights wants you to defer your javascript.
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...)
Strating from an example:
<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>
The question is: How to apply the Google suggestion to the example above?
回答1:
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.
来源:https://stackoverflow.com/questions/15871307/ultimate-solution-to-defer-javascript-and-jquery-after-page-is-loaded