0

I have multiple functions within multiple external JavaScript files that I want to load when the page loads. If I use "body onLoad" then one function always supersedes the other. How do I configure it so I can load each function from each file and have them load as soon at the page does?

I tried combining the files by putting both functions (only have 2 at the moment) into one javascript file, however whenever I use "document.getElementById("clockModule").innerHTML =" to output data to a specific div ID, the data is outputting to a single ID and they overlap one another

2 Answers 2

2

When you do window.onload = function(){ ... }, what you're doing is assigning a new value to window.onload, replacing whatever is assigned to it previously. This means there can only ever be one value. In the same way, innerHTML replaces the entire contents of the element.

Instead, use addEventListener to attach your event handlers and consider creating DOM nodes and attaching them using createElement and appendChild.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for explanation. I have no idea window.onload could only have a single value assigned to it, that makes a lot of sense
See MDN "window.onload = function() { init(); doSomethingElse(); };"
@Joseph Okay I tried figuring it out myself but I can't is there a more detailed explanation in regards to using addEventListener
0

During development, it's fine to load several separate .js files. However, once you're ready to publish to production, you'll want to roll all that .js into one file for performance purposes (and maybe even minify it). In any case, I always use DOMContentLoaded listener like:

document.addEventListener('DOMContentLoaded', function() {
  //do stuff in here.
  if(window.location.pathname === '/about'){
    //do page specific stuff in here.
  }
}, false);

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.