使用事件时,在关闭正文标签之前使用脚本标签的优点 [英] Advantages of script tag before closing body tag when using events

查看:142
本文介绍了使用事件时,在关闭正文标签之前使用脚本标签的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如今,似乎人们建议将script标签放置在结束body标签之前.

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>

如果立即运行脚本,这是一件好事,因为大多数DOM都已加载.但是,如果您使用onload或DOMContentLoaded事件调用主脚本怎么办?在这种情况下,如果将script标记放在文档头中似乎没有什么区别,因为直到DOM加载,您的代码都不会执行.

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.

使用onload或DOMContentLoaded事件运行脚本时,将script标记放置在封闭body标记上方还是在head上方真的有任何优势吗?

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?

另一方面,如果您不希望脚本在DOM加载之前执行,为什么不简单地将script标记放在结束body标记之前并立即运行它而不会发生任何事件.似乎这样可以节省几行代码,同时提供相同的功能.

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.

推荐答案

我认为,他们在可拆分的不同上下文中运行JS代码,因为主体的标记结尾(内联源)是顶级"代码,其中DOMContentLoaded处理程序是在事件侦听器函数中.脚本标记执行后也会执行DOMContentLoaded. 从笔者的经验中可以看出,DOMContentLoaded仅在无法控制标记的情况下有用.

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.

这篇关于使用事件时,在关闭正文标签之前使用脚本标签的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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