问题
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