Ad

Trying To Execute Two JavaScript Files Together With Window.onload

- 1 answer

I've got two separate JavaScript files linked to one HTML document and when I run it, it seems the second JS file overrides the first. I think it has to do with the window.onload being called in each file but am not sure how to work around that.

I've tried using window.onloadend on one of the JS files and window.onload on the other but with the same results, the window.onloadend is the only file that is executed.

file1.js

function init() {
    applyFunction();
    prefillForm();
    var applyForm = document.getElementById("applyForm");
    applyForm.onsubmit = validate;
}

window.onload = init;

file2.js

function init() {
    currentPage();
    timer();
}

window.onload = init;
Ad

Answer

Whenever you assign to an on- property, you will overwrite whatever was previously attached to that property, and when the event fires, only the latest handler will run. Use addEventListener instead:

window.addEventListener('load', init);

(put that in place of the .onload line in both files)

Or, if you don't have to wait for the entire document to load (including things like images), you might listen for DOMContentLoaded instead, which will trigger more quickly. The DOM and all elements will be populated, though not all resources may have been downloaded:

window.addEventListener('DOMContentLoaded', init);
Ad
source: stackoverflow.com
Ad