简体   繁体   English

关于javascript的快速问题(body-tag)

[英]Quick question about javascript (body-tag)

Does the page load faster if i use the javascript before the </body> tag? 如果在</body>标记之前使用javascript,页面加载速度会更快吗? Example: 例:

<body>

balbllb content

 <script type="text/javascript" src="jQuery.js"></script>
 <script type="text/javascript">
    $(function(){

    });
  </script>



</body>

The page will still load in the same amount of time, but it might be perceived as loading faster (ie you might see DOM element(s) appearing quicker). 该页面仍会在相同的时间内加载,但是可能会感觉加载速度更快(即,您可能会看到DOM元素显示得更快)。

If it was me, I would leave your jQuery.js reference in the <head> , and keep your custom stuff before the end of <body> . 如果是我,我会将您的jQuery.js引用保留在<head> ,并将自定义内容保留在<body>末尾之前。

I don't know whether it loads faster (I would be surprised) but in this case you no longer need to wrap your code in a $(document).ready as at that moment the document will be ready to be manipulated: 我不知道它是否加载得更快(我会感到惊讶),但是在这种情况下,您不再需要将代码包装在$(document).ready中,此时该文档将可以被处理:

<body>
    balbllb content
    <script type="text/javascript" src="jQuery.js"></script>
    <script type="text/javascript">
        // directly manipulate the DOM here
    </script>
</body>

Its not about anything happening faster. 它没有任何事情发生得更快。 Its the order in which things happen. 它发生的顺序。 Putting scripts at the bottom (right before the closing body tag) makes it so the rest of your content loads before loading the scripts, making it appear that its loading faster. 将脚本放在底部(紧接在body标记之前)可以使其余内容在加载脚本之前加载,从而使其加载速度更快。

The total page load time will be the same. 页面总加载时间将相同。 But the page will be perceived as loading faster since it will appear to the user faster. 但是该页面被视为加载速度更快,因为它将更快地显示给用户。 The "perception of loading faster" is not a conjecture, it is a fact, proven many times by psychologists. 心理学家多次证明,“感知更快的加载速度”不是一个推测。

Remember that if you load your JS libraries at the bottom of the page (as you should), then any dependent scripts must follow the libraries at the bottom. 请记住,如果您在页面底部加载了JS库(应该这样做),那么任何依赖脚本都必须遵循底部的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM