Sunday, May 30, 2004

Closures to the rescue

Simon Willison makes excellent use of closures in JavaScript to insert code for page load without interfering with other scripts trying to do the same thing:

function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } addLoadEvent(nameOfSomeFunctionToRunOnPageLoad); addLoadEvent(function() { /* more code to run on page load */ });

This is very excellent.

No comments: