kevinkt kevinkt - 3 months ago 25
Javascript Question

Multiple window onload functions with only Javascript

I have an external JS file that adds a window.onload function to the page.

The basic premise is that it loads up a popup window on your website whenever the user clicks on certain link class. It's written in PHP / JS so assume that the function works by itself.

Inside this JS file has the following code.

window.onload = function() {
var anchors = document.getElementsByClassName("vyper-triggers");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
if (isMobile.any()) {
window.open("$url");
} else {
document.getElementById("clickonthis").click();
}
}
}
}


Now my problem is when my user wants to add 2 different popup windows, the window.onload function doesn't stack. Also because this is an embedded javascript that my user adds himself, there is no way for me to put both functions inside one big window.onload function.

My user might put one JS file in one area of their site, and another JS file in another area, if that makes sense.

So how do I make it so that the window.onload function will stack no matter the placing of these external JS files on the page and considering that each function must be kept separate?

Answer

Rather than setting window.onload, you should use addEventListener. Listeners added this way will stack automatically.

window.addEventListener('load', function() {
  console.log('First listener');
});

window.addEventListener('load', function() {
  console.log('Second listener');
});

window.addEventListener('load', function() {
  console.log('Third listener');
});

If you have to support versions of IE before IE9, there's a polyfill which will make this work correctly.