I have a list of profile images which appear in a "menu drop down" div which is initially hidden via CSS. I would like to load these images dynamically (as a list) when each menu item is selected, so as to reduce the page loading time. How is this possible?
Asked
Active
Viewed 1.8k times
3
-
Hopefully, you mean you would like to cache these images. If you start loading them while they are being selected, there's a good chance that they will take a long time to load. – Alex W Oct 25 '12 at 04:26
-
2you can use jquery Lazy loading http://www.appelsiini.net/projects/lazyload – Usman Oct 25 '12 at 04:27
-
Have you considered loading the whole content with AJAX? http://en.wikipedia.org/wiki/Ajax_(programming) – Jan Oct 25 '12 at 04:37
4 Answers
3
Try to use:
$("#divID").html("<img style='position:absolute' src='path/to/the/ajax_loader.gif'>");
If you using ajax:
function sendAjax()
{
$("#divID").html("<img style='position:absolute' src='path/to/the/ajax_loader.gif'>");
// you ajax code
$("#divID").html(ajaxResponse);
}
you can also use document.getElementById('divID').innerHTML
instead of $("#divID").html()
. its also work fine
If you use this method, doesn't need to hide the div using css. its automatically remove after the ajax response.
1
Well, you can try this:
<div id="desiredDiv">
</div>
<script>
var images = [
'http://www.example.com/img/image1.png',
'http://www.example.com/img/image2.png',
'http://www.example.com/img/image3.png',
...
];
for(var i=0; i<images.length; i++) {
$('#desiredDiv').append('<img src="'+images[i]+'" alt="" />');
}
</script>

spenibus
- 4,339
- 11
- 26
- 35

Hussain Akhtar Wahid 'Ghouri'
- 6,527
- 8
- 50
- 85
-
i hope it serves your prob upto some extent , if not let me know – Hussain Akhtar Wahid 'Ghouri' Oct 25 '12 at 06:58
0
In your HTML leave out the src attribute on each image tag. Instead, add an attribute called data-src and give it the image url.
Then, when the menu is displayed, run the following script:
$('.menu-class img').each(function() {
$(this).attr('src', $(this).data('src'));
});
Said script requires jquery if you don't already have it

Doug
- 1,018
- 2
- 9
- 16
-
Although, as Alex W pointed out, you may want to do this in the document ready event instead of when the menu opens so the image is ready BEFORE the menu opens - not after. – Doug Oct 25 '12 at 04:36
-
1
-
2
0
You can keep the list of images in a JavaScript variable:
var images = [
'http://www.example.com/img/image1.png',
'http://www.example.com/img/image2.png',
'http://www.example.com/img/image3.png',
...
];
Then you can load the image whenever you need by creating the image tag:
var i = 0; // the index of the image in the list
var $img = $( '<img>' ).attr({'src':images[i]});
Just append the image to your div and it will be loaded automatically by the browser.

Mouad Debbar
- 3,126
- 2
- 20
- 20