Showing posts with label js. Show all posts
Showing posts with label js. Show all posts

Friday, September 25, 2009

Preload Images the Right Way

Sure, all of us cringe a little when we see that phrase. Even so, for things like overlays—of which modals and tooltips are members—preloading the background images is a reasonable thing to do. (I still don't fully endorse it, more on that later.)1.

I tried this preload code:


(function(){
    var i, img, imageLoader = {
        imagesToLoad: [
            'resources/css/images/btn-default-sprite.png',
            'resources/css/images/bg-tooltip-left.png',
            'resources/css/images/bg-tooltip-right.png',
            'resources/css/images/bg-tooltip-image-left.png',
            'resources/css/images/bg-tooltip-image-right.png'
        ],
        loadedImages: []
    };
    for(i in imageLoader.imagesToLoad){
        img = new Image();
        img.src = imageLoader.imagesToLoad[i];
        imageLoader.loadedImages.push( img );
    }
})();

The images didn't seem to be loading any sooner though. So I put a tracer in the list - an image source reference that I knew didn't exist. Then I fired up the page and looked at fiddler. (I would've looked at firebug's net tab, but I was troubleshooting IE6 specifically.) No 404s. So then I tried this code:


(function(){
    var imagesToLoad = [
        'resources/css/images/btn-default-sprite.png',
        'resources/css/images/bg-tooltip-left.png',
        'resources/css/images/bg-tooltip-right.png',
        'resources/css/images/bg-tooltip-image-left.png',
        'resources/css/images/bg-tooltip-image-right.png'
    ];
    $('<div class="no-print" style="position:absolute;left:-9999px"/>')
        .appendTo('body')
        .html('<img src="'+imagesToLoad.join('"/><img src="')+'"/>');
})();

And I got my 404.

For the purposes of this discussion, preloading doesn't mean loading the images before the rest of the page, it means loading them before they're used.

Saturday, May 2, 2009

How to Avoid CSS Hacks

I've decided to use a very tiny bit of javascript to free me of css hacks. I already use js to add a class "jsEnabled" to the <html> element so that I can style things differently if I know that javascript is going to swoop in and alter them later (tabs, carousels, etc). Taking this a step further, I put the browser name + version number in the html element classname. Then in the css, you can write ".ie7 .my-div {float:none;}" Sure, we're not supposed to rely on javascript. But we usually do. And this is just for minor tweaks anyway. The site will still *work* with js turned off, you'd just lose that tiny css tweak you made that relies on it.