1

I do have a JavaScript file, I want to include in my WordPress page, so I can execute a particular function in the onload event of the document's body element.

How do I best add my method to WordPress, so that it is executed, without breaking any other functions that might rely on the onload mechanism? I mean, I could simply redefine the body element and make it call my method, but maybe there are other plugins that need to use the same event handler.

Is there any mechanism within WordPress, so that I can append methods to the onload event (instead of redefining onload entirely)?

1) Redefine onload:

   <body onload="myFunc()">
     // ...
   </body>

2) Versus appending:

   <body onload="wp_Some_Magic_Onload_Hook()">
     // ...
   </body>

with

 function wp_Some_Magic_Onload_Hook() {
   myFunc();
   otherFuncs();
   // ...
 }

2 Answers 2

2

body.onload is a technique derived from ancient times. It leads to many conflicts, e.g. with multiple modules trying to listen for the event. Unless you are targeting browsers from those ancient times (e.g. IE 6), you might want to use a more contemporary solution.

If jQuery is available (and on most WordPress sites it is, otherwise, just wp_enqueue_script it), write your script like this:

function myFunc() {
  // Do awesome stuff here!
}
jQuery(myFunc);

This will call myFunc as soon as the document has been loaded. Make sure that jQuery will be loaded before your script is executed.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't you normally need a jQuery(document).ready(function(){...})wrapped around it so that the function runs when the DOM is ready for JS code to execute?
@RizkyFakkel jQuery(callback) is a shorthand, see jQuery(callback).
0

The difference is that window.onload is defined in the DOM Level 0 Event Model and will erase all earlier register events. It's an 'native' call from an old API.

The Event.observe from the prototype javascript framework will determine the best event attacher available. A facade pattern. In modern browsers, the addEventListener will be called - attachEvent in case of Internet Explorer below version 9. In old browsers the onload will be called.

It obvious that a facade will choose the best option available, like Event.observe for prototype or .load in case of jQuery for example.

The methods from the DOM Level 2 Event Model are preferred over the DOM Level 0 Event Model methods because they act as observers and don't erase previous handlers.

Event.observe(window, 'load', function() { 
     alert("Hello World!");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.