Christophe
Christophe

Reputation: 28174

External stylesheet vs. JavaScript-added style tag

I have multiple widgets that can be added to various Web pages. Each comes with its own stylesheet:

<link type="text/css" href="http://mySite/widget1.css" />
<script type="text/javascript" src="http://mySite/widget1.js"></script>

The stylesheets are specific to each widget and very short (5 to 10 declarations).

I am considering having the stylesheet created dynamically within the script, for two reasons:

Something like this, inserted in widget1.js:

var stylesheet=document.createElement("style");
stylesheet.innerHTML="#slideshow{width:500px;...";
etc...

Anything wrong with this? This sounds like a good idea to me, but when I look at other examples (like jQuery plugins) the css and js are always in separate files.

Upvotes: 2

Views: 533

Answers (4)

Christophe
Christophe

Reputation: 28174

My final choice was to create the stylesheet from within the script.

Besides reducing the number of http requests, the major benefit is actually that you can tweak the stylesheet before injecting it. This is especially useful for widgets, as you can adjust a class name, a color or a size at runtime.

At a larger scale, this is what some libraries like LESS and SASS are doing.

Upvotes: 0

kennebec
kennebec

Reputation: 104850

If you are creating a new style element, why not put the code for it in the js widget file it affects?

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

replacing two http requests with one should bring performance improvements

If you have your CSS in its own file, the browser can cache it, thus improving performance. Having JavaScript creating it will wind up making a bigger JS file, and it (the CSS) can't be cached. Also, JavaScript will have to generate the CSS, thus lowering performance.

Upvotes: 1

Quentin
Quentin

Reputation: 944550

That won't help at all with the HTTP requests. Adding a link to an external stylesheet with JavaScript is still going to demand an HTTP request to fetch it.

You would probably be better off using something like YUI Compressor to merge and minify the stylesheets for all the widgets you use into a single CSS file. Then include it in every page and let browsers cache it.

Upvotes: 3

Related Questions