Multiple Javascript-documents or how to solve Script not shooting

Hi

So I have noticed while going into Javascript that when I have several HTML-documents the code won’t execute sometimes. For example, I have both index.html and about.html… But that my Javascript is sometimes not shooting if I put Javascript from both the index.html and about.html in the same script-document. In this case it was “Javascript.js”.

So I had some Javascript that was from index.html, which was shooting correctly. But when I also had some cross Javascript form about.html, in the same document, one of them was not shooting at times while the other one was. Depending on which one came first in the Javacript-document.

I solved this by making the script from about.html be in that document itself rather than in the Javascript-js-document.

But how do pros do this? Is it really a good idea to have multiple scripts in different parts of the website/app or is this bad practice? Should it not all be in the same place for better practice?

How do I solve that problem? How do pros do this?

And could multiple scripts at different parts of the document make the app or website slower as well?

I am no pro, so I reduce the problem and try to do this in a jsfiddle. It is a good way to lower the threshold for others to help you.

Generally, multiple scripts slows down the site. But I do not think where you place it does matter. It does matter when it should be executed. Before or after the load.

But the upside is that your code may be more readable, when you split your javascript into small pieces.

There’s nothing wrong in having two different script for two different pages:

home.html
about.html

js/
 home.js
 about.js

If done right will help you avoiding sending useless bytes to the client with script never meant for that page :slight_smile:

1 Like

Aha so this is a common practice then ? :slight_smile:

Because it is basically impossible to make this work in only one js-document right?
Because they will shoot on top of each other and cross-firing

That’s not the case at all, you can certainly make everything work in one file, and make the loading/triggering event properly.

Is just that ideally is not wise to send to the client everything, even when is not needed.
But as always don’t start making premature optimizations.

This mostly happens when you have global stuff, e.g. variables, and don’t use proper scopes.

If you want to have one single js file, you could create a parent function for each single page, e.g. function home() and function about() and run the proper one in the specific page.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.