Tuesday, September 27, 2011

window.onload being used in multiple places within the same application included

Recently one of my team members ran into an issue where we had used
the window.onload to dynamically set some values in a cookie object.
Our application handles multiple javascript files and we had used
window.onload in another jsp also for another reason.

So,when multiple jsp files are trying to add different functions to the window.onload event, only the last function was executing. We developed a workaround by adding the function that chains the onload event functions. Below snippet gives an example of how we solved it.

function addLoadEvent(functionName) {
var firstonload = window.onload;

if (typeof window.onload != 'function') {
window.onload =
else {
window.onload = function() {
if (
firstonload ) {

and the actual function definition is in the original jsp and this
function is called from there. So the first time window.onload may
not be a function so we are setting it, On subsequent assignments,
window.onload exists, so whatever it holds will be wrapped up with the
new function. the list grows like that...

No comments: