Objective: With flash sometimes we might need to fetch external images (images from remote server). If we use those images in different pages of the application, then on each page (frames) we need to request server to fetch the images separately. Images loading might take time due to slow internet connection or bigger size of the images.
Solution:
We can fetch all the images when the application loads in the background and put those in a dictionary object. A dictionary Object behaves as a container, which keeps the images like a [key-value] pair where the key is name of the element and value is the image content. Basically we are caching the images at client side.
Before going to get the images from the remote server we can check if the image is already present in the dictionary. If the image is already present in dictionary then we can read from the dictionary and use it, else we can fetch the image from the server and save it in dictionary for later use.
Code Snippet:
import flash.utils.Dictionary; private var imageDictionary:Dictionary = new Dictionary(); private var imageLoader:Loader; /* * Method to handle image loading */ public function loadImage(imgURL:String):void { imageLoader = new Loader(); imageLoader.name = imgURL; // name of the loader as per the URL of the image passed in this.imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleImageLoadComplete); this.imageLoader.load(new URLRequest(imgURL)); } /* * Method to handle image load complete event */ private function handleImageLoadComplete(evt:Event):void { // Check if the image is present in the dictionary and then add the image to the dictionary if (!imageDictionary[evt.target.loader.name]) imageDictionary[evt.target.loader.name] = evt.target.loader.content; // Setting key name to store the image content } /* * Method to display image whenever required */ public function preloadImage(url:String):void { // check if the corresponding key is present in the dictionary object or not if(imageDictionary[url]) { var bitmap:Bitmap = Bitmap(imageDictionary[url]); bitmap.x = 0; bitmap.y = 0; bitmap.width = 560; // Set the width of the image. bitmap.height = 345; // Set the height of the image. this.addChild(bitmap); // Adding to the container to display the image. } else { loadImage(imgURL); } }
// we can call the preloadImage to check the availability of the image and display the image when required by passing the corresponding URL as parameter to check if any key exists
preloadImage(imageURL);
NB: loadImage function can be called at the beginning of the application either in the constructor with the number of image URLs that we want to fetch.
Advantages: – The images will be loaded and displayed very fast
– One time server trip will be there per image
Disadvantages: – Every time we start the application the dictionary object will be initialized
– To increase performance we should use limited number of images, as the caching itself can take more space