I don’t write full blown AJAX but I do code some JavaScript from time to time. One big tip I can offer other “casual” javascript coders, since many times a script must be executed after a page is loaded, is to STOP using window.onload=your_function;
The reason for this is simple – you should be APPENDING your script to the page loaded hook, not CLOBBERING any existing scripts that may be already attached. The “window.onload” method can only hook one function at a time and these days it’s common to use several third party scripts on a site. If you are not careful, you may be left scratching your head why something stopped working – because you accidentally stopped it from loading.
There used to be some clever workarounds for this, like making a function that checked onload and appending it to a list of functions to call and replacing it with your own onload. But with modern browsers today, all that mess is not needed. Just replace your code with this (albeit longer) code:
if (window.attachEvent) {window.attachEvent('onload', your_function);}
else if (window.addEventListener) {window.addEventListener('load', your_function, false);}
else {document.addEventListener('load', your_function, false);}
Tested working in all major modern browser (IE, Firefox, Safari, Opera) and it appends instead of replaces the onload process. Hope that helps!
Interesting, will this work with bbPress too? And where to put this? In the header? What if I want to use this on just 1 page (let say on index.php)? Any thoughts?
Greetz
aaaaaaaaaaaaaaaaaa
c.D
So just put all your functions into the function you’ve assigned to onLoad, right?
Brilliant!
Yes I like it, but you really have to ask the question if onload is the correct approach in the first place.
What about jQuery’s $(document).ready()?
Excellent – having a time getting a WordPress site to run both javascript SDMenus and Anarchy Media Player – your solution worked perfectly. Thank you.
Amazing thank you very much
Though I don’t know much about it, there’s lot of help in the web to be able to learn more about this topic and how you will deal with it.
Thank you very much for your great solution! I had big problems with window.onload but now everything works perfectly.
.
Thanks again and keep up the good word
Greetings,
Schiman
my function has a bunch of alert boxes that start and take a while to click threw. when ur done clicking threw it takes you to a new page automatically. is there a way to get the page to load while the function is happening?
thanks thanks thanks this is the best solution for window.onload