Personal tools

Jul 08, 2010

Scripted CSS Injection (or whatever better name you can find for this technique)

While trying to close a request for one of our customer for obtaining a random image portlet I tested an alternative way to deliver CSS. Using Javascript.

When Web pages load and run things

Let's start with CSS. Browsers load HTML source from the Web. Inside the page you will find resources that are CSS file. Immediately the resource is loaded and the rules inside are applied to your HTML.

Now switch to Javascript resources. For Javascript... it's the same. The Javascript code is executed as soon as it is found in the page...

...but for this reason, when we need to act using Javascript on an already loaded DOM, we rely onto Javascript events.

We read immediately the code, but the execution is postponed later, when the page is fully loaded.

As the use of jQuery became standard for those tasks (especially in Plone) we always use something like this:

jq(document).ready(function() {
    // do something
});

When this lead to problems

Although we have really no choice, there are some cases where this "postpone things" is not perfect: when we need to apply (using Javascript) CSS classes on page elements at page load time.

But we can't avoid making those actions when page is loaded.

If we don't rely on onload event, we have no ready DOM to traverse. So we can't load and change a DOM node if the page is not fully loaded (even if we put the Javascript script after the HTML that define the node).

<html>
<body>
    <div id="foo">Hello world</div>
    <script type="text/javascript">
    <!--
        var foo = document.getElementById("foo");
        alert(foo.innerHTML);
    // -->
    </script>
</body>
</html>

The code above is bad, even if you are using or not jQuery... So we really need to wait for the moment when DOM is ready. You can't act of the page DOM before it is fully loaded.

However: what is the problem applying CSS style when the DOM is loaded?

The nasty effect can be a visual flip.

The page in the browser show the DOM node with the original CSS style, then after some time (that can be not so brief sometimes if the page is full of elements and heavy scripts) the Javascript engine run your code, and the node is changed: your new CSS class or your new scripted style is applied.

<html>
<head>
    <style type="text/css">
    #foo {
        background-color: red;
    }
    </style>
    <script type="text/javascript">
    <!--
        window.onload = function() {
            ... MANY OTHER EXPENSIVE OPERATIONS
            var foo = document.getElementById("foo");
            alert(foo.innerHTML);
        }
    // -->
    </script>
</head>
<body>
    <div id="foo">Hello world</div>
    ... A LOT OF MANY AND MANY HTML NODES
    <script type="text/javscript">
    <!--
        var foo = document.getElementById("foo");
        alert(foo.innerHTML);
    // -->
    </script>
</body>
</html>

A practical example

A customer ask us to develop a Plone portlet that:

  • show some random images when the page is load
  • works behind a reverse proxy (Varnish)
  • works with Javascript disabled (accessibility and graceful degradation)

Step 1

Varnish is caching all our resource, images and also HTML for every page. We can't (and don't want) change this.
How to cache everything but some little images inside a portlet?

The idea is to use Javascript  for performing AJAX request for this portlet and obtain a structure of data. The cache of this kind of request can be avoided easily.

Step 2

So we are able to load an HTML for the portlet without images then, when the DOM is ready, we can populate the portlet waiting for the AJAX call to the server. For some time the visitor see and empty portlet that magically begin load images. The effect is pleasant (at least... it's not annoying).

But we can't!
The portlet must work also with disabled Javascript... So we must load random images also when the page is loaded.

NB: if the visitor use a browser with Javascript disabled, we can only give him some random pre-loaded images, but we can't prevent Varnish cache of the whole page. Reloading the same page will show him the same images for some minutes. This is acceptable for us (and for the customer!).

Step 3

The final result is to load the first "static" images in the portlet itself, then use Javascript as described at step 1: changing those images with new ones obtained from AJAX call.

This lead to the ugly visual flip effect I talked above.

I can't explain why (this is not my work), but see an empty section that is filled after a little delay is not ugly... instead seeing a set of images that suddenly change to other is... bothersome!

Step 4?

Ok, so we can simply load static images hidden by some CSS class, then using Javascript we can show them only after the AJAX call and...
Opss!

But in this way we don't see any image when Javascript is disabled!

Ok... step 4 aborted.

Scripted CSS Injection

The perfect world is the one where the step 4 is performed, but only with Javascript enabled.

I need a CSS that is loaded early like all other CSS in the page (so its style is applied immediately to the page) but only when Javascript is enabled.

I found a way to do this, but surfing the web I was not able to find other example like this one. So I called this approach Scripted CSS Injection (SCI)... maybe someone can point me to other original name or example?

However... how this works? Simply generating the additional CSS... with Javascript!
For this we use the standard window.write Javascript API. The window.write command is used commonly to write HTML inside windows (is more common to use it in popup windows for generating the contained HTML from scratch).

The additional Javascript is load in the page head section and it doesn't wait for DOM load. The one in our product is only one line:

document.write('<style type="text/css">.hideFlag img {display: none}</style>');

As I said at the beginning, Javascript is interpreted as CSS, so immediately when found in the page.
The browser will add to HTML the style node immediatly.

What is nice of SCI approach is obvious: a browser with no Javascript support can't add the CSS rule to the page!

Fairytale gone well

This technique finally lead us to a portlet that:

  • will show cached images if without Javascript support, but images are still random (chosen server side and changed with some delay)
  • will show random (and not cachable) images client side if Javascript is enabled
  • No ugly visual flip effects. With Javascript enabled static images are loaded hidden, then new dynamic ones are taken from the server and show. Thanks to SCI approach.

For more info, check the code of auslfe.portlet.multimedia.

comments powered by Disqus