Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If grouping front-end code helps reduce requests, why aren't more websites written on one html document?

Tags:

javascript

I guess what I'm asking is that if grouping JavaScript is considered good practice, why don't more websites place the JavaScript and CSS directly into one HTML document?

like image 254
Jordan Scales Avatar asked Jun 02 '12 04:06

Jordan Scales


3 Answers

why don't more websites place the JavaScript and CSS directly into one HTML document

Individual file caching.

  • External files have the advantage of being cached. Since scripts and styles rarely change (static) and/or are shared between pages, it's better to just separate them from the page making the page lighter.

    Instead of downloading 500kb of page data with embedded JS and CSS, why not load 5kb of the page, and load from the cache the 495kb worth of JS and CSS - saves you 495kb of bandwidth and avoids an additional 2 HTTP requests.

  • Although you could embed JS and CSS into the page, the page will most likely be dynamic. This will make the page load a new copy all the time, making each request very heavy.

Modular code

  • Imagine a WordPress site. They are built using a tom of widgets made by different developers around the world. Handling that many code stuffed in one page is possible, but unimaginable.

  • if some code just short circuited or just didn't work on your site, it's easier to take out that code linking the external file, rather than scouring the page for the related code and possibly accidentally remove code from another widget.

Separation of concerns

  • It's also best practice to separate HTML from CSS and JS. That way, it's not spaghetti you are dealing with.
like image 197
Joseph Avatar answered Sep 21 '22 14:09

Joseph


When you have a lot of code in a single document, it's harder to work with the code because you need more time to find the necessary string to change.

That is why it's good practice to divide code into separate files, with each of them solving its own special task, and then include them in code where it's necessary.

However, you can a write script which will join your files from the development version, which has many files, to a release version, which has fewer files, but this brings two problems:

  1. People are often lazy to do additional coding to create this script and then change it when the structure of your project becomes more complex.

  2. If you find a bug or add a small feature, you will need to rebuild your project again both in developed and release versions.

like image 22
DaneSoul Avatar answered Sep 19 '22 14:09

DaneSoul


They separated them so that multiple webpages can use the same file. When you change a single file, multiple pages can aromatically updated also. In addition, big HTML file will cause a long time to download.

like image 40
Derek 朕會功夫 Avatar answered Sep 21 '22 14:09

Derek 朕會功夫