Appending repeated images in web page with javascript - javascript

I want to use javascript to append some images to a div in the web page. Each new instance of the image will be in a loop that includes something like
pic=new Image()
pic.src="./images/xyz.jpg"
document.getElementById(div1).appendChild(pic)
This works but because there are lots and lots of repeated images chosen randomly, I think that each repeat will be fetching an image from the server that I already have and I wonder how to avoid this overhead.
There are various techniques on the web for cloning object so you might think that something along the lines of
appendChild(pic1)
pic2=clone(pic1)
appendChild(pic2)
would do the trick but it seems that the cloning includes the .src so there would be no saving. In any case, only one image appears!
Any Ideas?

Actually, if the picture has been downloaded once, the browser will not download another copy. So you can add as many of the same image as you like.

When reloading the two pages, I don't notice any difference in the rendering time (with Google Chome).
My guess is that you're using a browser with a slow JavaScript engine and/or DOM implementation. Also appendChild() can be slow. Create the innerHTML as a large String and assign it in one go. Alternatively, use CSS to display the images (using background-image and a fixed size) and just create empty DIVs. That should be faster than creating hundreds of image objects.
If you need it even faster, try CSS sprites.

Related

Is loading a blank image faster than multiple if statements?

My webpage uses a lot (1000+) gifs and displays different gifs using 'if' and 'getElementbyId', would it run quicker if I dropped the if(map(x,y)!=0){... to change the scr and just used a gif which was transparent?
Googled to heck but it's a hard question to word, if a same/similar has been posted please point me there.
Many Thanks
First you said about getElementById which is a part of javascript - A client side scripting language, so that is not a big reason to be worried about.
You said 1000+ .gif images.
Use concept of Sprites in this case
This will allow you to download all your images in one go.
This will also reduce some of downloading burden from your server.
To work with sprite technology, Visit this link, I believe this is what you need.
Create an Object Pool with Images and load them on the initialization step. Load them in batches and extend pool with new images if required.
While loading images show spinner. It will be loaded long for a first time, after that a browser will put them in cache.
If you have an opportunity to combine different little images in one (sprite), do it! because it is faster to load one big image, then a lot of little.

What is the most efficient way to store an image? HTML/CSS/JS

I am going to have a lot of images and trying to find the most efficient way of storing these images to keep the page snappy.
So far I have thought of just the two ways: load with javascript eg picture = new Image(); picture.src = "file.jpg"; and append / remove to the page as necessary, or load into <img> and set display:none.
Are there other options? what is considered the best way to do this?
The best way for a photo gallery (if thats what you are building) is usually to have several sizes of the images, at least two:
a smallish size that is highly compressed and thus have a small footprint: this is the image you load into grids and display in a page where there are multiple images
a larger image with lower compression and higher image quality - this is the one you show when people want to see details.
Since people most often come to the detailed image from a page where the small/fast loading version has already been shown, and thus is already in the browsers cache, you do a little trick and have instant photos, without preloading anything.
It goes like this:
On the details page you show the highly compressed small image in an image tag that has the dimension of the larger detailed version. You then load the larger detailed version in the background using new Image() with an onload event attached that changes the source of the image tag with the small compressed version to the large detailed version.
It looks great, works fast and users will love you ;)
PS: the best way to store images is the browsers cache, not js or the DOM, so if you truly wish to preload images, which is generally a bad practice (tho it can be necessary sometimes), make the browser fetch them for you in the background by including a css file that references them in styles that aren't applied to visual areas of your site.
I'm not sure about "efficient", but the most logical way would be not use the JavaScript to load an image (useless if you have JavaScript disabled) or to set the image as hidden via the display property (likewise, and the browser will probably just load the image anyway).
As such, a sensible suggestion would be to use boring old paging and display 'n' images per page. However, to bring this up to date, you could use "lazy" (a.k.a. "deferred") loading and load additional page content via Ajax as the user scrolls. However, it's key that this gracefully degrades into the standard "paged" behaviour if JavaScript is disabled, etc.
The perfect example of this in operation is Google's image search, and if you search here on StackOverflow you see a discussion of possible implementations, etc.
It's better to use javascript the way that you have it and then add it to the DOM as you need, as opposed to first adding it to the to the DOM and then hiding it because DOM manipulation is much slower and you may not use some images

Using a large image (file size) but not hinder load time?

My demo is here.
Basically, I have a HUGE image (19160px × 512px to be exact, just under 2MB) that I transition the backgroundx using javascript to make it appear as if a transformation was happening.
I cannot compress the image much more without ruining its quality dramatically. Is there another way that I can achieve this with the same level of cross-browser and not rely on plugins like flash, but have it load faster?
Have you considered making this a video?
It might improve loading time somewhat.
Also, another idea. Have you tried using only the first and last image, putting the last one on top of the first, give it opacity:0 and fade it in using JavaScript (e.g. jQuery)?
The effect won't be 100% identical to what you have now, but it might look good enough to please the client, and it would reduce loading time to a bare minimum.
If both ideas won't work for you, I think the first 10-12 frames could be compressed more effectively as GIF images. (It's an estimate, I haven't tried.) You would have to split the image into multiple div s to do that and change the method you use to switch the images, and you would have more requests, but it could be worth it.
If it is a jpeg, you can always use progressive encoding. it will become clearer as it is downloaded.
There is also an interlaced
"Progressive JPEG" format, in which
data is compressed in multiple passes
of progressively higher detail. This
is ideal for large images that will be
displayed while downloading over a
slow connection, allowing a reasonable
preview after receiving only a portion
of the data. -Wikipedia
Slice it like Google Maps.
If you want to change that many pixels on the screen at once, you'll have to get them to the client somehow. You could chunk it into multiple images and use something other than background-x, but then you expose yourself to other potential network interruptions along the way.
The only alternative I can think of to precomputed images like this one is to do the computation on the client - start with the full-colour image and manipulate it using the client's CPU. Your options here involve canvas or CSS3 or a plugin.
I'm not a big fan of Flash but in this case it seems like the right tool for the job (unless you need it work on the iPhone). If you don't have the Flash authoring tool you can use the free Flex compiler.
See http://www.insideria.com/2008/03/image-manipulation-in-flex.html
Make it into an animated gif? Break it up into individual parts to remove all the area that is obscured by content.

I want to load multiple images very fast on a website, what's the best method?

UPDATE: This question is outdated, please disregard
So.. my idea is to load a full manga/comics at once, with a progress bar included, and make sort of a stream, like:
My page loads the basic (HTML+CSS+JS) (of course)
As done, I start loading the imgs(the URLs are stored on JS var) from my server, one a time (or some faster way) so I can make a sort of progress bar.
ALTERNATIVE: Is there a way to load a compresses file with all imgs and uncompress at the browser?
ALTERNATIVE: I was also thinking of saving then as strings and then decode, they are mostly .jpg
The images don't have to show right away, i just need the callback when they are done.
XTML and HTML5 is acceptable
What is the fastest way to load a series of images for my website?
EDIT
Since #Oded comment.. the question is truly what is the best tech for loading images and the user don't have to wait everytime is turns the 'page'. Targeting a more similar experience like when you read comics in real life.
EDIT2
As some people helped me realize, I'm looking for a pre-loader on steroids
EDIT3
No css techs will do
If you split large images into smaller parts, they'll load faster on modern browsers due to pipelining.
ALTERNATIVE: Is there a way to load a compresses file with all imgs and uncompress at the browser?
Image formats are already compressed. You would gain nothing by stitching and trying to further compress them.
You can just stick the images together and use background-position to display different parts of them: this is called ‘spriting’. But spriting's mostly useful for smaller images, to cut down the number of HTTP requests to the server and somewhat reduce latency; for larger images like manga pages the benefit is not so large, possibly outweighed by the need to fetch one giant image all at once even if the user is only going to read the first few pages.
ALTERNATIVE: I was also thinking of saving then as strings and then decode
What would that achieve? Transferring as string would, in most cases, be considerably slower than raw binary. Then to get them from JavaScript strings into images you'd have to use data: URLs, which don't work in IE6-IE7, and are limited to how much data you can put in them. Again, this is meant primarily for small images.
I think all you really want is a bog-standard image preloader.
You could preload the images in javascript using:
var x = new Image();
x.src = "someurl";
This would work like the one you described as "saving the image in strings".
Spriting
Just have a look how facebook does it: http://b.static.ak.fbcdn.net/rsrc.php/z3JQK/hash/11cngjg0.png
One image that loads FASTER than series of small images. To display the icon you simply create a div with fixed dimensions, and move the background inside it. Your div works as a viewport for the big image. You use background-position to move to appropriate part of the image. Everything else is hidden.
Different domains
Something you probably didn't know - Internet Explorer has a limit of connections per server. You can read about it here: http://support.microsoft.com/?scid=kb;en-us;183110&x=17&y=11 (here are exact numbers).
What it means - if user is using IE7, he will be able to load ONLY 4 (or 2) files at the same time from your server regardless his internet connection speed.
To speed things up, you could create few subdomains: server1.mydomain.com, server2.mydomain.com, server3.mydomain.com etc - and then user can download many files a lot quicker, because you use different hosts to serve different files.
As done, I start loading the imgs(the
URLs are stored on JS var) from my
server, one a time (or some faster
way) so I can make a sort of progress
bar.
Your browser already downloads the HTML first, that's how it knows to load any JS/images you reference. You are trying to invent something that already exists.
Just make sure your manga is made up of lots of images of a known size, which you specify in your img tags. Most browsers have some sort of progress bar to show that it's loading resources for you. You're not going to make loading large images faster unless you improve either the speed at which your server serves them, or your user's internet connection, or you compress them to make your image files smaller (likely at the cost of image quality).
Note: JPG and PNG are already compressed.
You can try using a "CSS sprites" technique. Basically the idea is you use your favorite image editing program to stich all your images into a single image. It's faster to send this because you lose the per/file overhead in terms of encoding the image and sending the image. On the client side you use CSS to only select the portion of the total image that is used in any one place.
http://www.alistapart.com/articles/sprites/
http://www.fiftyfoureleven.com/weblog/web-development/css/css-sprites-images-optimization
AND/OR
You can use lazy loading to only load images when they come into view.
http://www.appelsiini.net/projects/lazyload
Image preloaders have been around for ages. You really do not need to load them all at once, you can do it on demand [when the person loads the next page, you can fetch the image after it]
My page loads the basic (HTML+CSS+JS) (of course)
As done, I start loading the imgs(the URLs are stored on JS var) from my
server, one a time (or some faster way) so I can make a sort of progress bar.
The images don't have to show right away, i just need the callback
when they are done.
If you want to load 10 images as fast as possible, place 10 <img> tags on the page, one for each image. Use Javascript to hide all the but the currently viewed image; add next/back links that use JS to hide the current image and show the next one. Many browser already have some form of progress bar, and by doing things with regular old HTML, it will function correctly.
You're trying to re-invent all this functionality with Javascript for no good reason. You're not going to do it better than the browser.
All that said, this is probably a bad idea. You might dump 15MB of comic pages into the browser window only to have the user leave after reading the first page. Rather than trying to pre-load all images, you should use JS to always keep the next page (or two) pre-loaded, not the entire thing.
Here's something you can try, which by happenstance I just coded up:
(function() {
var imgs = [ "image1.png", "image2.png", ... /* all your image names */ ],
index = 0,
img;
function loader() {
if (index >= imgs.length) return;
(img = new Image()).onload = loader;
setTimeout(function() { img.src = "/path/to/images/" + imgs[index++]; }, 1);
}
loader();
})();
Plop all your image names (or the ones you want to preload) into the array, and make sure this script starts up when your page(s) start loading. It'll work its way through the list of images, loading them, and then moving on to the next one when each image finishes. (The setTimeout call is to make sure that the "onload" handler doesn't get called while you're still inside a handler.)
You'd probably want to do this for lots of the "nuts and bolts" images for your whole site - in other words, each page would try to load images for everything. Once they're in the cache, of course, this won't take a significant amount of time. Alternatively, you could run this script only on a couple pages, like "login" screens and the main "home" page. Of course, if you've got a site like Flickr, then you probably wouldn't want to preload all your images :-)

Duplicate Flex Object in HTML without Re-Initializing

I am creating a flash object that does some heavy image lifting. What I am looking to do is load many flash objects onto the same page to take an image, modify it, and display it within the flash object.
The problem I am running into is that when I try to add 100 flex objects to the page, the browser freezes as it tries to re-load/initialize each instance. Once they are all loaded, the processing of the images goes by quick.
Does anyone know how to duplicate the flash piece without having to reload everything?
Another thought of mine would be to load the image into one flex object, and have that one modify the image tags using MHTML/data URI. Any thoughts?
The answer I came up with is using the data URI scheme. I send the image to a single flash object, have it run the pixel bender scripts and then output a Base64 image string to the data URI on the image tags.
For IE, which does not support the scheme, I will output the string to a php script that will return the decoded image. The reason I am doing so much work for this is because Pixel Bender is powerful and allows me to pass a lot of the processing to the client side. Also, in testing, applying all image manipulations using pixel bender is exponentially faster than doing it in PHP/GraphicsMagick.
You can't, Flex has to initialize, and that's a horrible horrible idea.
Flash is extremely CPU intensive, Flex doubly so since the interface itself uses a lot of power from the CPU to draw its interface effects.
Do whatever you need to, but don't initialize 100 Flex SWF's unless you want angry users.

Categories

Resources