I’ve searched Google for quite a while now but can’t find a suitable answer.
I have a website project that needs a popup gallery but that gallery should load on top of all other elements after a user clicks a link. Just like in Facebook when you open a video it creates a fixed div in front of all others and then loads the video.
In CSS I’ve tried "display: none"
but it slows down the loading of all other elements on page load. I should make it load only when needed so that the initial loading time won’t suffer.
Advertisement
Answer
You need to avoid setting the image’s src attribute until the time when you want to incur the overhead of loading the image.
Since you can’t set the src when rendering the page, you need to put it somewhere else so your script can find it. I suggest using a data attribute.
HTML:
<IMG data-src="http://mydomain/myimage1.png"/> <IMG data-src="http://mydomain/myimage2.png"/> <IMG data-src="http://mydomain/myimage3.png"/> <A id="MyLink" href="#">Click here to load images</A>
And your jquery
$("#MyLink").click(function(){ $("IMG[data-src]").each(function(){ $(this).attr("src",$(this).data("src")); }); });
The jquery will iterate through all IMG elements on the page, read the data-src attribute and stuff it into the src attribute, which will cause the images to load. Images that do not have a data-src attribute will get skipped (in case you have some normal images on the page that do not need the delayed loading behavior).