什么JavaScript应该包含在< head>以及包含在< body&gt ;?中的内容 [英] What JavaScript should be included in the <head> and what included in the <body>?

查看:119
本文介绍了什么JavaScript应该包含在< head>以及包含在< body&gt ;?中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对哪些JavaScript应该包含在哪些地方感到困惑?

I am confused about which JavaScript should be included where?

例如:


  • 在哪里应该包含jQuery库?在< head> 或结束< / body> 元素之前?

如果JavaScript定义在< body> 底部,那么它可以在内部使用吗? p>

  • 如果阻止并行下载,为什么它从来不会将CSS包含在底部?

    If the JavaScript is defined at the bottom in the <body>, can it be used inline in the body?


    推荐答案

    < script>元素



    脚本元素阻止了渐进式页面下载。

    浏览器一次下载多个组件,但当他们遇到外部脚本时,进一步下载,直到脚本文件被下载,解析和执行。

    这会伤害整个页面时间,尤其是在页面加载过程中出现多次时。
    b $ b阻止效果,您可以将脚本元素朝向
    页面的结尾,紧靠在结束标记之前。

    这种方式将不会有其他资源供脚本阻止。
    剩下的页面组件将被下载并且已经与用户接触。

    最糟糕的反模式是在文档头部使用单独的文件:

    The Place of the <script> Element

    The script elements block progressive page downloads.
    Browsers download several components at a time, but when they encounter an external script, they stop further downloads until the script file is downloaded, parsed, and executed.
    This hurts the overall page time, especially if it happens several times during a page load.
    To minimize the blocking effect, you can place the script element toward the end of the page, right before the closing tag.
    This way there will be no other resources for the script to block. The rest of the page components will be downloaded and already engaging the user.
    The worst antipattern is to use separate files in the head of the document:

    <!doctype html>
    <html>
    <head>
        <title>My App</title>
        <!-- ANTIPATTERN -->
        <script src="jquery.js"></script>
        <script src="jquery.quickselect.js"></script>
        <script src="jquery.lightbox.js"></script>
        <script src="myapp.js"></script>
    </head>
    <body>
    ...
    </body>
    </html>
    

    更好的选择是合并所有文件:

    A better option is to combine all the files:

    <!doctype html>
    <html>
    <head>
        <title>My App</title>
        <script src="all_20100426.js"></script>
    </head>
    <body>
        ...
    </body>
    </html>
    

    最好的选择是将组合脚本放在页面的最后:

    And the best option is to put the combined script at the very end of the page:

    <!doctype html>
    <html>
    <head>
        <title>My App</title>
    </head>
    <body>
        ...
        <script src="all_20100426.js"></script>
    </body>
    

    JavaScript Patterns,由Stoyan Stefanov
    (O'Reilly)。 Copyright 2010 Yahoo !, Inc.,9780596806750。

    这篇关于什么JavaScript应该包含在&lt; head&gt;以及包含在&lt; body&gt ;?中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆