If I have some card images for a Javascript game, what is the most efficient way to display those images?
Is it best to just create a new object with the same image URL? Should I preload all images then hide them and clone an instance of the image object? Is the开发者_运维问答re another method?- Pre-load them of course.
- Use sprites whenever possible, for instance, you could load each suit in one image. Then you could load each card as the background of a div.
- As long as you load the images from the same URL. The browser should use the clients locally cached file, instead of requesting it from the server.
- Cloning should be good, but itwill have to be a deep clone, otherwise manipulating one will effect all other clones.
It's a good idea to preload them all, so they show up as needed with no delay even the first time they are requested. Make sure they are caching on the user's side.
Have you thought about using a CSS-Sprite for your images? That would probably speed things up a lot too since you wouldn't have to request headers for 52 different images. You could put 13 cards on a row and have 4 rows of cards one for each suit and then just adjust background-position
accordingly for each card, and you'd be guaranteed that once one card loads they've all loaded.
An option that I do is called CSS Spriting. Basically what you do is join all your images into one big images, then you use CSS to display just the image you want by setting the width
and the left
attributes. The advantage is that all the images are loaded at once, since its just one big image.
As far as most efficient way to show them: probably replacing the "src" attribute of a generic img element. As for preloading: probably a good idea. all you need to do to preload an image is something like
var preloadImg = new Image();
preloadImg.src = "blah";
that loads it into the cache and you're good to go.
精彩评论