0

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?

Front_End_Dev
  • 1,205
  • 1
  • 14
  • 24

3 Answers3

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