views:

42

answers:

3

This is probably a really simple one but I couldn't find the answer.

I have the following JavaScript/jQuery code where I am trying to create loading messages:

// preload an image to use for dynamic loading icon whenever requested
$(document).ready(function() {
    var loadingIcon = document.createElement('img');
    loadingIcon.src = '../images/ajax-loader.gif';
    window.loadingIcon = loadingIcon; // chache in global var
});

I wanted to cache the image on load so I'm not requesting it each time I want a loading message. Am I actually acheiving this with the above code?

The idea is that there's a lot of dynamic content on the page, and at any time I might have several different loading icons active.

I add the loading icon wherever with:

$('#myElem').appendChild(window.loadingIcon);

This doesn't actually work though, when I try to show a new loading icon, it just moves the previous one, so I can't have more than one on the page at a time.

I'm assuming I need to clone the element?

I tried to wrap the element in a jQuery object to use clone with $(window.loadingIcon).clone() but that didn't work (the function errored).

+1  A: 

Try creating the image as a jQuery object:

var $loadingIcon = $('<img src="../images/ajax-loader.gif" />');

And then you should be able to clone it when you need to use it:

$('#myElem').append( $loadingIcon.clone() ); 
DMA57361
I can't get this to work, not sure why.
fearofawhackplanet
@fear - What error are you getting?
DMA57361
+2  A: 

You could clone the element, yes. But you can just as well create a new <img> element. If the image src has already been loaded by the browser, the image data will be cached and no further network-load will occur. You don't need to cache the element itself to cache the resource it's pointed at.

bobince
A: 

javascript has a native cloneNode method, at least in IE7, which is all I have at the moment. I'm pretty sure it's cross browser.

this should do what you want:

$('#myElem').appendChild(window.loadingIcon.cloneNode()); 
lincolnk