我应该使用IIFE或窗口onload来初始化吗? [英] Should I use IIFE or window onload to initialize?

查看:88
本文介绍了我应该使用IIFE或窗口onload来初始化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个代码段均有效:

Both of the following code snippets worked:

在js文件中使用IIFE:

Using IIFE in js file:

(function initialize() {
  txtInput = document.getElementById('txtInput');
  txtResult = document.getElementById('txtResult');

  txtInput.value = "0";
  txtResult.value = "0";

}());

在html文件中的窗口加载事件上调用initialize():

Calling initialize() on window load event in html file:

window.addEventListener('load', initialize, false);

这是一种比其他更好的方法;在表现还是其他方面?就目前而言,我更倾向于向窗口对象添加事件监听器,因为它更具可读性。

Is one a better approach than other; in terms of performance or otherwise? As it stands right now, I am leaning more towards adding event listener to the window object, because it is more readable.

推荐答案

这取决于您希望代码运行的时间。如果您希望代码尽快执行,您可以使用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.


  • <底部的code>< script> 将在从服务器获取后执行。

  • DOMContentLoaded 在HTML解析器读取< / html> 后基本执行。

  • 非常简化 window.onload 在所有CSS之后执行,< img> es和< script>

  • <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.
  • very simplified 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.

这篇关于我应该使用IIFE或窗口onload来初始化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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