简体   繁体   English

Javascript。代码的position对性能有影响吗?

[英]Javascript. Does the position of the code affect performance?

I was searching for ways and tricks to improve my javascript code performance.我一直在寻找提高 javascript 代码性能的方法和技巧。 I would like to know what are the best practice to use in order to have best performance.我想知道为了获得最佳性能而使用的最佳实践是什么。

Does the position of the script (in the header, in the body, in the middle of the code or at the end) affect the performance?脚本的 position(在 header 中,在正文中,在代码中间或末尾)是否影响性能?

Thanks for any tips.感谢您的任何提示。

If there is a lot of JS, put it at the end of the document.如果JS较多,放在文档末尾。 Although this makes no difference on load time, the user will see the page sooner and can begin to read it while your js loads, as opposed to seeing nothing until your JS is downloaded (which is what happens when you put it in the head).尽管这对加载时间没有影响,但用户会更快地看到该页面并可以在您的 js 加载时开始阅读它,而不是在您的 JS 下载之前什么都看不到(这是将它放在头部时发生的情况) . It merely makes the download appear faster.它只是让下载看起来更快。 This would also solve the problem mentioned above about the script executing on an unfinished document, although for that, an even better solution is to use window.onload().这也将解决上面提到的关于在未完成的文档上执行脚本的问题,尽管为此,更好的解决方案是使用 window.onload()。

I don't think it has performance impact but it can have logic impact.我认为它不会对性能产生影响,但会产生逻辑影响。 If your javascript is not deferred and it tries to use a dom element declared after the script, the script will not run.如果您的 javascript 没有延迟并且它尝试使用在脚本之后声明的 dom 元素,则脚本将不会运行。

i dont think so that the position of the code will affect the performance because whenever a jsp is loaded its with all its content and script so the complete code is already present in the browser, and it wont matter where your script lies in the code.我不认为代码的 position 会影响性能,因为每当加载 jsp 时,它的所有内容和脚本都已存在于浏览器中,因此您的脚本位于代码中的位置无关紧要。

Speaking without actually testing, and for any performance discussion that's dangerous, I find it hard to imagine that it will have any significant impact.没有实际测试就说,对于任何危险的性能讨论,我很难想象它会产生什么重大影响。

Once the code has been parsed then it's location is surely irrelevant?一旦代码被解析,那么它的位置肯定是无关紧要的? So the only thing that it could impact is initialisation.所以它唯一可能影响的是初始化。 However I can't see that position within an HTML file can be significant, the whole file would need to be interpreted by the browser.但是我看不到 HTML 文件中的 position 可能很重要,整个文件需要由浏览器解释。

You can place the JavaScript, anywhere within your web page.您可以将 JavaScript 放置在 web 页面的任何位置。 Also best practice is to load the JS at the end最好的做法是在最后加载 JS

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

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