Running JavaScript code before other onload functions

To run JavaScript code during the onload event at specific times relative to other code in the same event, simply replace the window.onload function with a new function that runs the previous onload function at the desired time.

window.onload = function(prevOnloadFunction) {
   return function(ev) {
      if (! ev) ev = window.event;
      ... any JavaScript code here runs before other onload code ...
      if (typeof prevOnloadFunction == "function") prevOnloadFunction();
      else alert("prevOnloadFunction should be a function, not " + typeof prevOnloadFunction);
      ... any JavaScript code here runs after other onload code ...

The previous window.onload function is passed as a parameter to a function that builds the new function (via (window.onload) near the end) so that it is resolved when the new function is being defined. However, since the inner function does not include a parameter list, its code, including the call to the previousOnloadFunction() will not be executed until the onload event has been triggered.