admin管理员组

文章数量:1291594

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!

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!

Share Improve this question asked Mar 22, 2013 at 12:18 Patrick ClanceyPatrick Clancey 1,3702 gold badges15 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

You should use document.readyState property:

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

本文标签: javascriptHas windowonload event already firedStack Overflow