0

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;
2
  • For what it's worth the correct course of action here would be to just place your scripts at the end of the <body> tag and not the start of the head - that would let you solve the onload/DOMContentLoaded check entirely and just write your code. Also consider doing work in multiple scripts in modules :] Commented Apr 28, 2019 at 9:27
  • I'll definitely make a note of doing that next time, thanks! Commented Apr 28, 2019 at 9:34

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

Or eventually you can rename Init functions to be not unique and in HTML call an anonymous function, which calls them both sequentially. And in HTML call them:

load = () => {
   Init1();
   Init2();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.