I need to call a function on page load. Typically this would be handled with a body onload call, however I'm in a CMS that reuses the body tag on multiple pages. I only need the script to run on a single page. Is there a next-best-location to initiate an onload function?
Asked
Active
Viewed 2,186 times
0
-
Easiest may be to put it right before the closing body tag. – j08691 Mar 20 '12 at 20:09
3 Answers
2
Use the window.onload event:
window.onload = function() {
// do stuff
};
If you have access to jQuery, you can use one of the .ready() syntaxes:
$(document).ready(function() {
// do stuff
});
OR:
$(function() {
// do stuff
});

jbabey
- 45,965
- 12
- 71
- 94
1
If you are using jQuery, you can add a load event on window:
$(window).on('load', function(){
// do stuff here
})
You also have DOM ready with jQuery:
$(function(){
//stuff here
});

slowBear
- 264
- 2
- 11
-
The first code block is more inline with what you are asking I think. – slowBear Mar 20 '12 at 20:06
1
You can instantiate it in a separate js file, so it will only be called when that file is loaded, not the CMS template. i.e.
window.onload = function(){
// Do stuff
};

gaffleck
- 428
- 4
- 8