CategoryJavaScript

Link element load event support for CSS Style Sheet includes, finally!

In the long history of developer attempts at creating a method of loading CSS Style Sheets via LINK tags with load event support, there has been a lot of FAIL and almost no WINNING! Oddly enough, Internet Explorer has supported a load event on LINK tags for as long as I can remember, but Firefox and the Webkit bunch…not so much.

What are people doing currently to service this need? Well here’s an example of half-baked solutions that have surfaced over the last couple of years on Stack Overflow (I have added my solution to the list, so up-vote it!). Most developer have been reduced to loops that look for the new sheet in the StyleSheet object at short intervals or even loading the link tag in an iframe and using the frame’s onload event, two methods that cause me to puke on my shoes on principle.

The Solution

Well web devs, today is the day. Yup, CSS Style Sheet loading via LINK tags with pretty damn legit load event support is a reality:

var loadCSS = function(url, callback){
    var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = url;

    document.getElementsByTagName('head')[0].appendChild(link);

    var img = document.createElement('img');
        img.onerror = function(){
            if(callback) callback(link);
        }
        img.src = url;
}

The code above creates a LINK tag for your CSS file and inject it into the head of the document, there's certainly nothing odd about that. Next comes the interesting part, it creates an IMG tag and adds your CSS file location as src parameter of the element then injects it into the page. The browser parser downloads the file and attempts to parse it, which predictably fails as it is the wrong MIME type. That failure triggers the error event on the image element. We know the file is present at that point, so the load event you pass to the function is fired from inside the image element error event, the image element is then deleted from the document. Whether cached or not, this method will fire your load event for any CSS file you include, when the file is in the cache it is called immediately - which is a huge benefit.

Try it out!

Here it is a live demo, I have added an alert as the load event default for example sake:

Programatically Convert CSS named colors to RGB & HEX

Converting color values between different formats is commonplace on the web. Whether it is a JavaScript-assisted animation, color picker, or modifying a color’s attributes, there are many circumstances where color manipulation is essential to front-end development. One color format particularly hard to work with is CSS named colors. Named colors are widely supported in A-grade browsers, here’s a list of common named colors courtesy of w3schools.

So what’s the problem?

The problem with named colors is the difficult lengths to which a developer must go to manipulate and use them practically. It is relatively easy to use them statically in style-sheets (though I prefer RGB or HEX, in that order), but more interesting uses are usually dynamic ones that result from user input.

As developers, we think in RGB and HEX values because that is the world we are immersed in, users however are more likely to think in black and white as opposed to #000000 and #FFFFFF. What does that mean to you as a developer? Let’s say you have a color picker that transitions a target element to and from colors based on user input, how do you allow a user to type in “purple” and effectively animate your element from #000000 to “purple” without a gigantic, pre-populated, name colors object? Furthermore, what developer would ever want to spend their time assembling and maintaining such a list?

“Computed Styles, I’ve heard so much about you.”

Most developers are aware of computed styles, but just in case you are not, here’s a definition to prime the pump:

Computed Styles methods provide used values for all CSS properties of an element in their most reduced format. Computed Styles is a somewhat costly operation as all the values must be calculated each time the method is called.

One note on the above definition – the used values returned by computed styles methods are always reduced to a common format, this is most evident with the transform property, it is reduced to the common matrix(a, b, c, x, y) representation of the value regardless of which format (rotate, scale, skew, translate, etc.) the style was applied with.

Now that we have a better understanding of computed styles, let’s find out how we can use them to overcome the use of dumb, static named color tables.

As it turns out, all browsers have internal methods for reducing named color values to HEX or RGB formats, some are just harder to access than others. Mozilla, Chrome, and Safari all have a common global method for retrieving computed styles – window.getComputedStyles() – that takes as an argument the element you are requesting the computed styles for.

Opera uses the same mechanism as other non-IE browsers to report computed styles, however named colors are not converted to HEX or RGB values when retrieved with the computed styles method. Instead, Opera strangely chooses to reset the property in question on the style object of the element to the calculated HEX or RGB value of the named color.

IE provides an object, currentStyles, that is accessible directly from the element. Unfortunately IE does not convert named colors to RGB or HEX through any sane means – even in IE9. It is possible to get to the calculated HEX and RGB values of named colors in IE, but as you’ll see below, it isn’t pretty.

Bringing it all together

So let’s get smart about this! With the goods on computed styles I crossmedibrowsertated and came up with the String native methods “colorToHex()” and “colorToRgb()” with a little help from the sextacular MooTools javascript framework:

© 2024 Back Alley Coder

Theme by Anders NorenUp ↑