MHK
MHK

Reputation: 320

What is the best way to attach JS, CSS and all other vendor files?

Lets suppose you've a PHP site, and there is alot of Javascript and CSS files.
But every JS & CSS file will not be attach on all pages.
Some like : You've 18 CSS files and 23 JS files and the sum of these files is 31. And you've 3 PHP files i.e :

  1. index.php
  2. about.php
  3. contact.php

Not all these 31 files will attach with on every single PHP page.
5 CSS and 10 JS files will attach with index.php
As it is 10 CSS and 12 JS files will attach with a about.php and so on...
Now the question is that, "What will you do with these 31 files, either you put all these file on one page then include on all the PHP files or attach with respactive page?"

Upvotes: 0

Views: 46

Answers (2)

Zaptree
Zaptree

Reputation: 3803

The choice is yours and really depends on how far you want to improve your performance. You really have 2 choices:

  1. The easy choice is to just compile all the files into a single css and a single js file and include them in all your pages.

  2. The harder choice but a bit more performant (depending on the size of all your javascript and css) is to have one css/js file with all the shared css/js and then another css/js file for each page with the specific css/js for that page.

Note that solution 2 is not only more difficult to pull off but it might even be slower in some cases. What slows down your performance the most is having multiple http requests. So if you decided to load those 31 files in your page without compiling them, that would be very detrimental to your performance.

Some good tools for compiling your css and js are:

http://gulpjs.com/ or http://gruntjs.com/

which run on nodejs https://nodejs.org/

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116110

Combine all your CSS files into one file. If you use a tool for that, you can keep separate source files (easy to work with) and compile them and minimize them into a single file for download.

Do the same with JavaScript.

That way, you've got only two files that are also quite small. These files can be statically served, and with the proper headers, the client will cache them very well. There is some overhead of sending more data than you need for each page, but you've got much fewer request because everthing is in a couple of files and those files can be cached between page requests.

Examples of online tools to try out the idea:

Upvotes: 1

Related Questions