Trying To Execute Two JavaScript Files Together With Window.onload
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;
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);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM