更新时间:2023-08-23 13:43:58
这取决于您希望代码运行的时间。如果您希望代码尽快执行,您可以使用IIFE,但如果您不使用它来保护变量和/或不污染全局范围,那么使用IIFE毫无意义。
It depends when you want the code to run. If you want the code to execute ASAP you can use an IIFE but there is really no point using an IIFE if you don't use it to protect your variables and/or not polluting the global scope.
(function initialize() {
// do somthing
}());
或
// do somthing
将在同一时间点执行。
如果您想延迟执行,那么Web开发人员通常会使用三个时间点。底部是< script>
,DOMContentLoad和window.onload。
If you want to defer execution there are three points in time usually used by web devs. <script>
s at bottom, DOMContentLoad and window.onload.
DOMContentLoaded
在HTML解析器读取< / html>
后基本执行。 window.onload
在所有CSS之后执行,< img>
es和< script> 已加载code>。
<script>
s at bottom will execute after they are fetched from the server.DOMContentLoaded
basicly execute as soon as </html>
has been read by the HTML parser.window.onload
executes after all CSS, <img>
es and <script>
s have been loaded.请注意,实际上,使用 async等属性
和推迟
< script>
s,这更复杂,。这就是为什么有大量的资源加载器可用。
Note that in reality, with attributes like async
and defer
on <script>
s, this is more complex, . This is why there is a mountain of resource loaders available.