简体   繁体   中英

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.

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.

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.

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.

如果要创建新的样式元素,为什么不将其代码放入它会影响的js小部件文件中?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM