Advantages of script tag before closing body tag when using events [duplicate]

本秂侑毒 提交于 2020-04-11 04:47:52

问题


These days it seems like people recommend placing the script tag just before the closing body tag as such..

        <script src="//javascript.js"></script>
    </body>
</html>

If you are running the script immediately, this is a good thing because most of your DOM has mostly loaded. However, what if you are using the onload or DOMContentLoaded events to call your main script? In this case, it seems that it would make no difference if placing your script tag in the document head, since your code will not execute anyways until the DOM loads.

When using the onload or DOMContentLoaded events to run your script, is there really any advantage to putting your script tag above the closing body tag vs the head?

On the other hand, if you don't want your script to execute until DOM has loaded, why not simply place your script tag before the closing body tag and run it immediately without any events whatsoever. Seems like this would save a few lines of code while providing the same functionality.


回答1:


I think, they run JS code in littile diffrent context ,because tag end of body (inline source) is "top-level" code where as DOMContentLoaded handler is in an event listener function. DOMContentLoaded is also executed after script tag execution. As i see from my littile experience DOMContentLoaded is only useful in cases when i cant control the markup.



来源:https://stackoverflow.com/questions/26441730/advantages-of-script-tag-before-closing-body-tag-when-using-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!