Wednesday, May 7, 2014

Injecting CSS with Javascript

Why injectCSS? Why make it? What is it solving?

  • The primary goal was to create an easy way to include multi-line (lots) of CSS using Javascript.
  • Can reduce number of files in a JS plugin or project (My goal was one).
  • A test run at jsperf.com shows that injecting CSS rules for a vast number of elements is very fast.
There are already some existing CSS injection tools, but I wanted something dead-simple. There is a great library called VeinJS, which does so much more than mine in many different ways. But after perusing through the examples I knew that I would have to dismantle my CSS too much. What I wanted was something like what you will see in the example below.

Example Usage

With RequireJS

With no dependencies

Compatability

Tested successfully on:

  • Chrome (+mobile)
  • Firefox
  • Safari (+mobile)
  • IE 10+
Due to the older IE browsers not allowing the innerHTML property to be set on certain elements, this will not work in them.

Download

The code is on GitHub. Download, use and modify as you please.

No comments: