Griffon_Kato
Griffon_Kato

Reputation: 31

Is it okay to have 1 .js file for each html page?

Can I write it like this? Won't I have issues in terms of how fast my website loads?

for index.html:

<html>

<body>
  <script src="index.js"></script>
</body>

</html>

for about.html:

<html>

<body>
  <script src="about.js"></script>
</body>

</html>

for contact.html:

<html>

<body>
  <script src="contact.js"></script>
</body>

</html>

I just want to clear things up. Thanks in advance!

Upvotes: 3

Views: 6333

Answers (4)

vgru
vgru

Reputation: 51204

The right approach is to split your code into multiple functions as appropriate.

To address loading performance, use a minifier which will minify and bundle all your code (include JavaScript, CSS and HTML). You won't be able to outperform an actual minifier anyway.

Depending on the technology you are using, minification can be a step during your build/deployment procedure, or a plugin for your CMS which will minify and cache your files as they are being accessed.

Upvotes: 0

rahim.nagori
rahim.nagori

Reputation: 666

Yes you can use it like this way, your website load faster. But if you include all the JS to all the files, it'll load slower because loading time is increased coz all the three files load for all the three pages.

Or a different approach.

Try to convert all the three file into only 1 (This way you'll reduce the repetitive function) Then include this file to each file. By storing the file to cache memory, file only download (load) once then it'll be used from the cache memory. This way your speed will be increased. Refer to the following link: https://www.html5rocks.com/en/tutorials/appcache/beginner/

Try to research as much as possible. You'll get your solutions.

Tick right (✓) if my answer is helpful for you.

Upvotes: 1

Clinton Ray Mulligan
Clinton Ray Mulligan

Reputation: 56

You should extract out common features among all the javascript code you run on different pages.

Imagine index.js has a function to create a list. And about.js has the same function. When it comes to updating that function you will want to change it in one place. Not the five pages you have.

As for speed if every page has a link for list.js file, it will only need to be downloaded by the browser once. It's code will be cached and used in all the other pages requested.

Upvotes: 3

Thomas James Tiam-Lee
Thomas James Tiam-Lee

Reputation: 691

The pages load separately so having a script in another page does not affect how fast the current one loads.

In my opinion, if you are very concerned about the speed it is more important to ensure that you are only loading the scripts that you need in the current page.

Upvotes: 0

Related Questions