admin管理员组

文章数量:1295739

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?

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?

Share edited Oct 25, 2012 at 5:19 iono 2,7631 gold badge31 silver badges38 bronze badges asked Oct 25, 2012 at 4:23 user200261user200261 331 gold badge2 silver badges4 bronze badges 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 Commented Oct 25, 2012 at 4:26
  • 2 you can use jquery Lazy loading appelsiini/projects/lazyload – Usman Commented Oct 25, 2012 at 4:27
  • Have you considered loading the whole content with AJAX? en.wikipedia/wiki/Ajax_(programming) – Jan Commented Oct 25, 2012 at 4:37
Add a ment  | 

4 Answers 4

Reset to default 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.

Well, you can try this:

<div id="desiredDiv">
</div>
<script>
var images = [
    'http://www.example./img/image1.png',
    'http://www.example./img/image2.png',
    'http://www.example./img/image3.png',
    ...
];
for(var i=0; i<images.length; i++) {
    $('#desiredDiv').append('<img src="'+images[i]+'" alt="" />');
}
</script>

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

You can keep the list of images in a JavaScript variable:

var images = [
    'http://www.example./img/image1.png',
    'http://www.example./img/image2.png',
    'http://www.example./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.

本文标签: javascriptLoading Images into Div DynamicallyStack Overflow