Attempting to run a pair of JavaScript files simultaneously using the window.onload event

I'm facing an issue where two JavaScript files linked to a single HTML document are conflicting with each other. It seems like the second JS file is always taking precedence over the first one. I suspect that this might be related to both files using window.onload, but I'm unsure of how to resolve it.

I attempted to use window.onloadend in one of the JS files and window.onload in the other, but unfortunately, the window.onloadend script ended up being the only one executing.

Here's a snippet from file1.js:

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

window.onload = initialize;

And here's a snippet from file2.js:

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

window.onload = initialize;

Answer №1

When you set an on- property, it will replace whatever was previously linked to that property. When the event occurs, only the most recent handler will execute. It is recommended to use addEventListener instead:

window.addEventListener('load', init);

(replace the .onload line in both files with this)

Alternatively, if immediate loading of the entire document (including images) is not necessary, you can opt for listening to DOMContentLoaded, which triggers faster. At this point, the DOM and all its elements will be ready, although not all resources may have finished downloading:

window.addEventListener('DOMContentLoaded', init);

Answer №2

Another option is to consider renaming the Init functions to make them non-unique, and then using an anonymous function in HTML to call both of them sequentially. In your HTML code, you would call them like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When starting a new project with Angular 7, the option to set up routing is automatically included without asking for confirmation

After switching from Angular 6 to version 7, I encountered an issue while creating a new project in CLI using ng new [app-name]. It simply starts without giving me the option to include routing or styling in my project. Just a heads up, I am currently run ...

Instructions on calculating the sum of a checkbox value and a textbox value

Here, my goal is to dynamically calculate the total value of selected checkboxes (Checkbox1 and Checkbox3) with the value in TextBox1, and then display the sum in TextBox2 without the need for any button click event. <div> <asp:Tex ...

Having trouble importing a CSS file into a Vue.js single file component?

I am attempting to include 2 CSS files within the style tag of my Vue.js single-file component. <style > @import '../assets/styles/jquery-ui.js.css'; @import '../assets/styles/jquery-ui.css'; </style> However, I am ...

Creating an interactive text using Javascript functions

I am attempting to create an interactive text using JavaScript. While I can achieve this by creating a new function for each element, I realize that this approach will result in an excessive number of functions. Could anyone point out what is incorrect wi ...

Utilizing modal functionality in CakePHP 3 (or: Incorporating JavaScript within Controllers)

I have a typical form that was created using cake/bake. After the form is submitted, my controller checks a simple condition: If condition A is met, it will just save the data using patchEntity($foo, $this->request->getData()) If condition B is me ...

Deactivate the action triggered by a jQuery click event

$('document').ready(function(){ //textoverflow($('.content'),100); $('span').click(function(){ //disable textoverflow function & output full text }); }); function textoverflow(ele, num){ ele.each( ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

Options in the dropdown menu

After browsing online, I came across a functional example that I would like to replicate in a similar manner. Is there a way to show 2 different prices and currencies for the same selection in a drop-down menu without having separate drop-downs for each c ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

Configuring the start_url and scope within the manifest.json file for a React Progressive Web App

Can you explain the distinction in manifest.json between using start_url as "." versus "./", and likewise, setting scope as "." versus "./"? I am currently migrating a React app behind a reverse proxy server accessed through https://www.example.com/scorer ...

Guide on using PHP to remove the trash icon glyphicon

I am currently creating a data table that includes various actions, one of which is the option to delete a row from both the table and the database. My challenge lies in figuring out how to successfully delete a particular row by simply clicking on the Tr ...

When implementing JWT for route authentication, the webpage remains frozen in one spot

Currently, I am in the process of making modifications to a project. The front-end is built using Vue 2.0 and the back-end utilizes Node.js Express. To ensure security, I have implemented the JWT approach by requiring authentication for all pages except th ...

Organizing Dates in a Kendo Grid: How to Filter and Sort a DateTime Field

I am working with a datetime column in my Kendo Grid that displays values like this: 2014-04-11 12:43:41.720 To simplify the display, I have changed the template to show only short dates: 04/11/2014 The reason for not sending preformatted data to the col ...

How to Build an Express.js Query by Using a URL Parameter?

Is there a way to retrieve specific data from my MongoDB database based on the URL? For example, if I navigate to localhost:3000/phones, I want to fetch all entries with the category "phones", and if it's localhost:3000/laptops, I need data related to ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

There is an issue with the project where main.jsbundle, Foundation, and Security are missing, resulting in

I've noticed that I am missing the main.jsbundle file in my project and I'm unsure how to resolve this issue. Should I delete the file, or is there a specific step I can take to fix it? Attached is a screenshot showing where the file should be l ...

Displaying information on a webpage using URL query parameters

I am currently utilizing Next.js. Here is the organization of my files: --courses (directory) -course.js (file) --chapters (directory) -[chapter].js (file) One of my chapters is named "hello-world" and will reside in [chapter].js I desire th ...