延迟 JavaScript 解析 - Google Page Speed

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7206483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:21:10  来源:igfitidea点击:

Defer parsing of JavaScript - Google Page Speed

javascriptjqueryperformancegoogle-pagespeed

提问by Jitendra Vyas

All of my JavaScript files are already at the bottom but Google Page Speed is giving this suggestion to improve speed:

我所有的 JavaScript 文件都已经在底部,但 Google Page Speed 给出了这个提高速度的建议:

Defer parsing of JavaScript

88.6KiB of JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering. http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js(76.8KiB) http://websiteurl/js/plugins.js(11.7KiB) http://websiteurl/(109B of inline JavaScript)

延迟 JavaScript 解析

88.6KiB 的 JavaScript 在初始页面加载期间被解析。推迟解析 JavaScript 以减少页面渲染的阻塞。 http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js(76.8KiB) http://websiteurl/js/plugins.js(11.7KiB) http://websiteurl/(内联 JavaScript 的 109B)

This is the my html (example)

这是我的 html(示例)

<html>
<head>
<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<head>
<body>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>
    <script src="js/plugins.js"></script>
    <script>$(document).ready(function() {
            $("#various2").fancybox({
                'width': 485,
                'height': 691,
            });
        });</script>
    </body>
    </html>

What should I do to increase performance by using defer?

我应该怎么做才能通过使用 defer 来提高性能?

Is it only for Google chrome or for all?

是仅适用于谷歌浏览器还是适用于所有人?

回答by Vince Kronlein

If you're looking for page performance then first and foremost you should move those scripts to the bottom of your page to allow the other assets to load.

如果您正在寻找页面性能,那么首先您应该将这些脚本移动到页面底部以允许加载其他资产。

Also use dns prefetch in the head to set the base domain for google-code

还可以在头部使用 dns prefetch 为 google-code 设置基域

<link rel="dns-prefetch" href="//ajax.googleapis.com">

Since this is just a small piece of code, you could simply add it to your plugins.js file at the bottom then defer the plugins file.

由于这只是一小段代码,您可以简单地将其添加到您的 plugins.js 文件底部,然后推迟插件文件。

<script src="js/plugins.js" defer></script>

That's what I'd do anyway, all my sites are optimized to 98 and 97 respectively in yslow and page speed.

无论如何,这就是我要做的,我所有的网站在 yslow 和页面速度方面都分别优化为 98 和 97。

Hope it helps.

希望能帮助到你。

-V

-V

回答by Randhir Yadav

Add in <script type="text/javascript" defer="defer">tag like that it works for me.

添加这样的<script type="text/javascript" defer="defer">标签,它对我有用。

<script type="text/javascript" defer="defer" src="<?php echo $this->getSkinUrl();?>js/jquery.bxslider.js"></script>

回答by idrarig

I see this is an old question, but since I was looking for a good answer myself, I am going to share the method I currently use.

我看到这是一个老问题,但由于我自己正在寻找一个好的答案,我将分享我目前使用的方法。

As far as inline Javascript is concerned, what I do is change all the typeattributes to text/deferred-javascript, or something similar, so that the code within the script tag is not evaluated during page load. Then I attach a function to the page onloadevent; said function finds all the scripts matching the type above and evaluates the code inside using eval(). I know in general eval()is evil but it seems to be helpful here.

就内联 Javascript 而言,我所做的是将所有type属性更改为text/deferred-javascript或类似的内容,以便在页面加载期间不会评估脚本标记中的代码。然后我将一个函数附加到页面onload事件;所述函数查找与上述类型匹配的所有脚本,并使用eval(). 我知道一般来说eval()是邪恶的,但在这里似乎很有帮助。

For external Javascript files, I do something very similar. Instead of adding the script tags to the page, I record them and insert them one-by-one after page load has completed.

对于外部 Javascript 文件,我做了一些非常相似的事情。我没有将脚本标签添加到页面,而是记录它们并在页面加载完成后一一插入。

One problem I'm having is that if one of the inline deferred Javascript contains an error (say a parse error), the subsequent scripts are not loaded (but that might depend on my current implementation).

我遇到的一个问题是,如果内联延迟 Javascript 之一包含错误(比如解析错误),则不会加载后续脚本(但这可能取决于我当前的实现)。

回答by Fareed Alnamrouti

Hi recently we have created an opensource nodejs framework called "elegant framework" that help you building fast web application and we succeeded to get 100% google page speed in both desktop and mobile in all pages : you can check it at:

嗨,最近我们创建了一个名为“优雅框架”的开源 nodejs 框架,它可以帮助您构建快速的 Web 应用程序,我们成功地在桌面和移动设备的所有页面中都获得了 100% 的谷歌页面速度:您可以在以下位置查看:

https://developers.google.com/speed/pagespeed/insights/?url=getelegant.com

https://developers.google.com/speed/pagespeed/insights/?url=getelegant.com

there is a lot of things you can learn from it by viewing the page source also if anything you cannot understand please comment so i can help you with

您可以通过查看页面源代码从中学到很多东西,如果您有任何不明白的地方,请发表评论,以便我可以帮助您

so far you can try this method:

到目前为止你可以试试这个方法:

// Load script element as a child of the body
function loadJS(src, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if (script.readyState) {  //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                if (callback) {
                    callback();
                }
            }
        };
    } else {  //Others
        script.onload = function () {
            if (callback) {
                callback();
            }
        };
    }
    script.src = src;
    document.body.appendChild(script);
}
// Load style element as a child of the body
function loadCSS(href,callback) {
    var element = document.createElement("link");
    element.rel = "stylesheet";
    if (element.readyState) {  //IE
        element.onreadystatechange = function () {
            if (element.readyState == "loaded" || script.readyState == "complete") {
                element.onreadystatechange = null;
                if (callback) {
                    callback();
                }
            }
        };
    } else {  //Others
        element.onload = function () {
            if (callback) {
                callback();
            }
        };
    }
    element.href = href;
    document.body.appendChild(element);
}
// Load All Resources
function loadResources() {
    // css
    loadCSS("/compressed/code-mirror-style.css?please1");
    loadCSS("/compressed/all.css?please2");

    // js
    loadJS("/compressed/code-mirror.js", function () {
        loadJS("/compressed/common.js", function () {
            $("[data-lang]").each(function () {
                var code = $(this).addClass("code").text();
                $(this).empty();

                var myCodeMirror = CodeMirror(this, {
                    value: code,
                    mode: $(this).attr("data-lang"),
                    lineNumbers: !$(this).hasClass('inline') && !$(this).hasClass('no-numbers'),
                    readOnly: true
                });
            });
        });
    });
}

// Check for browser support of event handling capability
if (window.addEventListener) {
    window.addEventListener("load", loadResources, false);
} else if (window.attachEvent) {
    window.attachEvent("onload", loadResources);
} else {
    window.onload = loadResources
}

回答by Sparky

That's probably a generic response/suggestion for when it encounters a certain level of performance.

当它遇到一定的性能水平时,这可能是一个通用的响应/建议。

Although, it specifically mentions jQuery, a plugin, and 109 bytes of inline JavaScript. Do you have any inline JavaScript? Are you also placing your JavaScript includes at the bottom of the <body>?

虽然,它特别提到了 jQuery、一个插件和 109 字节的内联 JavaScript。你有任何内联 JavaScript 吗?您是否还将 JavaScript 包含放在<body>?

Example

例子

Loading Performance article

加载性能文章

EDIT:

编辑:

Based on recently posted HTML...

基于最近发布的 HTML...

As a test, remove these two items to see if it makes any difference:

作为测试,删除这两项以查看是否有任何区别:

<!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->



<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.5.1.min.js"%3E%3C/script%3E'))</script>


Also, the warning message mentions 109 bytes of inline JS, yet I don't see anything like that in the HTML you've posted.


此外,警告消息提到了 109 字节的内联 JS,但我在您发布的 HTML 中没有看到类似的内容。