I’m currently working on a script to be placed on a 3rd-party site…in order to test it I’m opening the 3rd party’s site and running the script in the browser’s console (Chrome). Some code I need to executed on window.load(), but that code isn’t being executed with this method of testing. I’m assuming it’s because the code bound by load to the window is being bound after the load event has taken place, thus never being triggered. My question has two parts:
-
Is the reason that window.load is not being triggered in fact because it’s being added after the load event has been triggered? Or is this wrong and there is likely a problem elsewhere?
-
How best can one simulate events triggered on load when appending javascript through the console like this?
if(document.readyState === "complete"){will detect if the load is already complete.You could easily use an else and then put in the load event handler if it hasn’t finished loading yet. Something along the lines of:
What I like to do is define a
pageLoadedtype function that I can run at a later point with my code, that way I can call it immediately if the page is already loaded, or let the load handler call it when the page load does fire. Something like:Of course, since you tagged your question as jQuery you could always just wrap all your code in jQuery’s handy dandy ready function shorthand:
This passes your anonymous function to jQuery where it will do something very similar if not identical to the above vanilla javascript.