JS 脚本应该放在页面哪个位置 head body foot

本文探讨了将JavaScript文件放置在HTML文档不同位置对页面加载速度的影响。研究发现,将JS文件置于页面底部可以避免阻塞并行下载,从而提高加载效率。同时,文章也提到了CSS文件应置于文档头部以实现页面渐进渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们平时在页面上写JS 是放在头部<head>中呢 还是放到body 最下面 能更优化?

查了一番资料,推荐 放在页面底部如:

<html>
    <head>
        <title>My awesome page</title>

        <!-- CSS -->
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">
        <link rel="stylesheet" type="text/css" href="...">

    </head>
    <body>
        <!-- Content content content -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
        <script type="text/javascript" src="..."></script>
    </body>
</html>

WHY?

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. More...

CSS

A little bit off-topic, but... Put stylesheets at the top.

While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. More...

参考:

http://stackoverflow.com/questions/196702/where-to-place-javascript-in-a-html-file

https://developer.yahoo.com/performance/rules.html#js_bottom=

转载于:https://www.cnblogs.com/miralce/p/6278966.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值