Use or not use CSS / JS within PHP?

5

Using CSS / JS within PHP, is there a difference if used in an external file for example? Many pages have CSS / JS inside and also externally, would not it be easier to put all together than splitting one part in code and another externally on the same server?

What is the correct way to use them? And why?

    
asked by anonymous 10.06.2014 / 23:37

2 answers

7

It's all about speed and resource saving .

Placing all of the code inside the page is impractical, as repetitions of scripts and style sheets on all pages generate a very large and unnecessary flow of data.

To give you an idea, let's assume your CSS / JS has a total of 100kb. If you put all the code inside the page, a thousand hits will generate a total of 98mb transferred, a waste of bytes.

By putting CSS and JS in external files, they are downloaded only on first access .

This was one of the main arguments of the tableless movement, advocating that the use of CSS would also bring more speed and economy of resources beyond the aesthetic gain.

As a general rule, have your PHP generate codes that are used only on that page and / or depend on user preferences. If your system allows the user to change the color of an element, it is okay to generate CSS within the page.

On the other hand, exaggerating the dose and spreading your code in many different script files will increase the number of GET requests, which, in addition to slowing down the site, will also be more expensive (services such as Amazon S3 charge for number of GETs).

So, the ideal is:

  • leave your scripts and style sheets out of HTML;
  • combine JS and CSS files before moving from development to production.
11.06.2014 / 02:29
1

Hello, my friend.

In addition to the issues cited by @Ifarroco, using CSS and JS scripts in external files also helps to create cleaner, more standardized code. Let's say your CSS will be used on several pages. By creating the same in a separate file, you can use it where you need it, just by inserting the file link. The same goes for JS.

I hope I have helped.

    
11.06.2014 / 19:31