Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to dynamically loading/unloading javascript and css stylesheets?

Background:

I'm putting together a site that will use ajax as a primary method of changing the content. That way the main frame and images will not have to be constantly reloaded with every page change. The main frame has its own site.css stylesheet.

Question 1:

Is it worthwhile to put all the stylesheet information into a single stylesheet? I think that this would make the website less modular. Everytime a new page or content is added/removed the css would have to be updated (given the content requires different style information).

Question 1.1:

Same question but with javascript.

Question 2:

If it is worthwhile (as I think it is) to have multiple stylesheets, is it beneficial to unload a stylesheet when its not in use. For example, I load the profile.php page so I dynamically load the profile.css. The user then changes to the settings.php page, I unload the profile.css and load the settings.css. Is this constant loading/unloading going to tank performance or even save on website size?

Question 2.1

Same question as above but applied to javascript functions.

like image 669
Spidy Avatar asked Mar 04 '11 04:03

Spidy


2 Answers

Once your javascript or css file is downloaded to the machine, it is cached by their browser. So, you don't incur the additional cost of another HTTP request. Lazy loading the scripts and stylesheets could make sense, but there is no sense in unloading these web assets once they have already been sent to the client.

It is good to use some sort of mechanism to compile your scripts and stylesheets to minimize the initial http requests to one per asset type. Having only one stylesheet and one javascript file would be an architectural nightmare in many cases, but that doesn't mean that you can't still present it to the browser that way. I use .NET, so I'm not sure how you handle this in PHP, but I'm sure the functionality is out there.

like image 95
smartcaveman Avatar answered Nov 15 '22 15:11

smartcaveman


Answer 1:

This is all about balance. You should keep different CSS and JS files, but combine them all into one before deploying (one CSS file and one JS file). Basically there's no need to develop with one big file because there are tools that can compile them for you.

The tricky part (depending on the complexity of your site) is figuring out which CSS and JS code gets used frequently enough to be called on every page. If you have code that only gets used on one page, you should probably dynamically load it...unless your whole site only has 5 pages. Like I said, balance.

Answer 1.1 and 1.2:

No, not worthwhile. As soon as you load the CSS and JS files, they get cached on the user's machine. So unloading them is pointless.

like image 32
Bryan Downing Avatar answered Nov 15 '22 15:11

Bryan Downing