0

I need to load 3 images from another page. This is my code

<script> jQuery(document).ready(function($) { var ids = ['#sk6x4', '#sk6x4a', '#sk6x4c']; var tabs = ['#tab1', '#tab2', '#tab3']; function getInfo() { $.each(ids, function (i, id) { $.ajax('/my-url', { success: function(data){ var imgSrc = $(data).find(ids[i] + ' img').attr('src'); $(tabs[i] + ' img').attr('src', imgSrc); } }); }); } }); </script> <ul class="nav nav-tabs" role="tablist"> <li class="active" id="tab1"><img src="" id="imageTriangle"/></li> <li id="tab2"><img src="" id="imageArc"/></li> <li id="tab3"><img src="" id="imageScat"/></li> </ul> 

This code works but wery slow. Images load very slowly. How i can make it faster? What is the right way to load images by ajax?

P.S. Images are optimized

5
  • 1
    Is the ajax call slow, or the image downloads? Maybe you need to optimize the images. Commented Dec 2, 2014 at 19:28
  • Images are optimized. Commented Dec 2, 2014 at 19:29
  • .each looping always makes the script slow try for loops Commented Dec 2, 2014 at 19:32
  • what is the cost of loading that other page (where the images live)? Is there some heavy server-side stuff going on to render that page? Maybe loading the images directly from their source location, rather than pulling them out of HTML, would be faster? Commented Dec 2, 2014 at 19:43
  • Where is getInfo called? With that snipplet it would take a really long time since it is never triggered. lol Commented Dec 2, 2014 at 19:44

1 Answer 1

2

First of all, you are making multiple ajax requests. It would be better to make just one, and return the URLs with JSON or something. Secondly, you don't even need ajax to load images. You can do like this:

$(document).ready(function () { var ids = ['#sk6x4', '#sk6x4a', '#sk6x4c']; var tabs = ['#tab1', '#tab2', '#tab3']; function getInfo() { $.ajax('/my-url', { // ajax call to get urls success: function (data) { $.each(ids, function (i, id) { var imgSrc = data.urls[i] //assuming that data is an array that contains the urls var img = $("<img /> ").attr('src', imgSrc).load(function () { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('Error...!'); } else { $(tabs[i]).html() } }); }); } }); } }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Good point about not making multiple AJAX requests - but I don't think we can assume the OP's endpoint returns JSON data in an array. It seems to be a real page load returning an HTML document.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.