使用window.onload的最佳实践 [英] Best practice for using window.onload

查看:140
本文介绍了使用window.onload的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发Joomla网站/组件/模块和插件,我经常需要能够使用JavaScript在页面加载时触发事件。大部分时间都是使用 window.onload 函数完成的。

I develop Joomla websites/components/modules and plugins and every so often I require the ability to use JavaScript that triggers an event when the page is loaded. Most of the time this is done using the window.onload function.

我的问题是:


  1. 这是在页面加载时触发JavaScript事件的最佳方式还是有更好/更新的方式?

  2. 如果这是在页面加载时触发事件的唯一方法,那么确保不同脚本可以运行多个事件的最佳方法是什么?


推荐答案

window.onload = function(){}; 有效,但是正如你可能已经注意到的那样,它允许你只指定一个听众

window.onload = function(){}; works, but as you might have noticed, it allows you to specify only 1 listener.

我会说更好/更新的方式这样做会是使用框架,或只是使用原生 addEventListener attachEvent 的简单实现(对于IE)方法,它允许你删除事件的监听器。

I'd say the better/newer way of doing this would be to use a framework, or to just to use a simple implementation of the native addEventListener and attachEvent (for IE) methods, which allows you to remove the listeners for the events as well.

这是一个跨浏览器的实现:

Here's a cross-browser implementation:

// Cross-browser implementation of element.addEventListener()
function listen(evnt, elem, func) {
    if (elem.addEventListener)  // W3C DOM
        elem.addEventListener(evnt,func,false);
    else if (elem.attachEvent) { // IE DOM
         var r = elem.attachEvent("on"+evnt, func);
         return r;
    }
    else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}

// Use: listen("event name", elem, func);

对于window.onload案例使用: listen(load,window ,function(){});

For the window.onload case use: listen("load", window, function() { });

编辑我想通过添加其他人指出的宝贵信息来扩展我的答案。

EDIT I'd like to expand my answer by adding precious information that was pointed by others.

这是关于 DOMContentLoaded (Mozilla,Opera和webkit nightlies目前支持此功能)和 onreadystatechange (针对IE)事件可以应用于文档对象,以了解文档何时可以被操作(无需等待所有图像/样式表等加载)。

This is about the DOMContentLoaded (Mozilla, Opera and webkit nightlies currently support this) and the onreadystatechange (for IE) events which can be applied to the document object to understand when the document is available to be manipulated (without waiting for all the images/stylesheets etc.. to be loaded).

对于跨浏览器的支持,有很多hacky实现,所以我强烈建议使用这个功能的框架。

There are a lot of "hacky" implementations for cross-browsers support of this, so I strongly suggest to use a framework for this feature.

这篇关于使用window.onload的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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