Ultimate solution to defer javascript and jquery after page is loaded

断了今生、忘了曾经 提交于 2020-01-01 18:56:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!