Preventing unstyled content before jQuery loads

Friday, February 18, 2011

jQuery is a very powerful tool but because of it's size it can be quite slow to load, and on some older devices it can also be slow to "boot up" and become ready for action (I'm looking at you iPad/iPhone!)

Why is this a problem?

In my case the problem is that jQuery loads after the main page body and then executes. This takes time. One of the actions the jQuery needs to do is to hide() an element, however before the jQuery is ready the element is visible. This means that when jQuery is finally ready there is a noticeable "pop" of UI as the element disappears!

"Why don't you just hide it be default" I hear you ask? Because some people have JavaScript turned off. That content should still be accessible to them, so we need to show it.

The solutions

The solution is to add a tiny bit of JavaScript to the head of the page that will add a js class to the <HTML/> element so we can create styles accordingly.

1<html> <head> <script> document.documentElement.className += "js"; </script> </head> ... </html> 

As a bonus we can also start with a no-js class so that we can also style for the opposite scenario. However, in this case we need to find and replace the no-js class from the html.

1<html class="no-js"> <head> <script> document.documentElement.className = document.documentElement.className.replace( /(?:^|\s)no-js(?!\S)/g , 'js' ); </script> </head> ... </html> 

Then you can add styles for each option as needed:

1/* special styles for when there is no JS*/ .no-js .my-element { display: "block"; } /* special styles for when there is JS*/ .js .my-element{ display: "none"; } 

Other posts


Tagged with: