Search code examples
javascriptcssstylesheet

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:

  • I find it painful to maintain two separate files
  • replacing two http requests with one should bring performance improvements

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.


Solution

  • 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.