Question

I have a script that manually preloads all images that will be required. It looks like this:

<script type="text/javascript">
(new Image()).src = "/images/buttonpinkpressed.png";
(new Image()).src = "/images/smallbuttonpinkpressed.png";
</script>

Actually, there is a lot of such entries for every type of button and other elements. The worst of all is that the project is in progress and new buttons are being added daily, so it's easy to forget add them to the list.

Now I want to use one universal script that preloads everything in use.

It should enumerates all elements with a jQuery-like selector (say, $('buttons') to get all buttons) in the document, then - and this is the hardest part to me - find the style which is the result of the element's class and 'active' class (not to be confused with :active pseudoclass, though, there should not be any difference).

For instance, there is a button:

<button type="button" class="small pink"><p>Menu</p></button>

And there is the following CSS:

button.pink.large
{
    background-image: url('buttonpinknormal.png');
}
button.pink.large.active
{
    background-image: url('buttonpinkpressed.png');
}
button.pink.small
{
    background-image: url('buttonpinksmallnormal.png');
}
button.pink.small.active
{
    background-image: url('buttonpinksmallpressed.png');
}

Obviously, for this button the preloaded image should be the last one, since 'small' and 'pink' are explicitly defined and 'active' is what we are looking for:

button.pink.small.active
{
    background-image: url('buttonpinksmallpressed.png');
}

So, the question is how to filter the styles.

Regards,

UPDATE

As you can see, initially the button has no 'active' style. It's being added with a script on touch event (because Android Webkit doesn't support real :active). That's why the image should be preloaded from another script. And, yes, I see run-time loading of active-state images on click, it looks UGLY.

Was it helpful?

Solution

Use a sprite and just change the background-position, that way the browser only has to do 1 request, and you won't have to do a preload since the normal state should be visible. And, switching between states is lightening fast since its just re-positioning the rendered image (not that separate images is slow, just that it is less efficient)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top