0

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).

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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() ); 

Comments

1

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()); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.