Has window.onload event already fired

╄→гoц情女王★ 提交于 2019-12-07 01:58:44

问题


I have a small javascript util which may get preloaded, lazy loaded or loaded on demand. When it's initiated it adds some stuff to the DOM. It's low priority and if it's preloaded it can wait for the onload event to fire before running, but if it's lazy loaded it can go ahead and run immediately.

Currently It's checking to see if the ID of the footer element exists to determine if it should add an event listener to the window onload event or just run. e.g.

if ( document.getElementById("footer") ){
   Init()
} else {
   if (window.addEventListener){...}
   else if (window.attachEvent){...}
}

Although currently working, this is obviously a pretty poor solution. Any non jQuery related suggestions on improving this gratefully received!


回答1:


You should use document.readyState property:

if (document.readyState === 'complete') {
   //do stuff
}


来源:https://stackoverflow.com/questions/15570139/has-window-onload-event-already-fired

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