2010-08-06 32 views
5

Ho un piccolo problema che ho appena trovato, dopo aver pensato che questo progetto fosse terminato. Ha funzionato perfettamente sul mio server locale ma quando ho spinto il codice in diretta le immagini possono impiegare mezzo secondo per caricarsi correttamente causando una piccola miniatura della pagina da far apparire sopra un'immagine di caricamento. grrrajax - controlla le immagini caricate prima di scrivere alla pagina

alt text http://img815.imageshack.us/img815/985/loading.jpg

Così che cosa sta accadendo? Innanzitutto una funzione viene eseguita su window.load che ha creato un numero elevato di elementi di elenco con una gif di caricamento come l'immagine di bg.

Poi questa funzione schiocca un tag <img> nel primo elemento della lista, con una onload che chiama una seconda funzione

Questo secondo cicli di funzione un file XML e avvolge l'URL nella xml in un <img> tag e mette nel prossimo vuoto LI. Questo è dove sta il problema. Al momento inserisce lo <img src=$variable onload=loadnextimage() /> nella voce Elenco prima che sia effettivamente caricato.

Il mio codice:

$(window).load(function() { 
      txt=""; 
      for(d=0;d<100;d++) 
      { 
       txt=txt + "<li class='gif' id='loading"+d+"'></li>"; 

      } 
      document.getElementById('page-wrap').innerHTML=txt; 
      document.getElementById('loading0').innerHTML="<img src='images/0.jpg' onLoad='loadImages(0)' />"; 
     }); 
     function loadImages(i){ 
      i++ 
      $.ajax 
      ({ 
       type: "GET", 
       url: "sites.xml", 
       dataType: "xml", 
       async: "true", 
       success: function(xml) 
       { 
        var img = $(xml).find('image[id=' + i + ']'), 
        id = img.attr('id'), 
        url = img.find('url').text(); 
        $('#loading'+i).html('<img src="'+url+'" onLoad="loadImages('+i+')" />').hide(); 
        $('#loading'+i).fadeIn(); 
       } 
      }); 
     } 

ho la sensazione può essere abbastanza difficile il raggiungimento di questo come l'ho istituito, e ho la sensazione che potrebbe essere necessario creare un oggetto img e aspettare che a caricare???

Una volta che la pagina è stata memorizzata nella cache, il caricamento ovviamente funziona bene, ma è un po 'difficile da caricare prima, quindi ho bisogno di aggiustarlo. any advice welcome :) thanks

risposta

2

A mio parere, stai pensando in modo difficile. A volte la soluzione sta cambiando il modo di pensare. Dipende completamente da te. One of my favorite related books.

Il mio suggerimento è qualcosa di simile al codice qui sotto. Non è esattamente quello di cui hai bisogno, ma ...

Demo on Fiddle

HTML:

<div class="frame" title="Tochal Hotel"> 
    <div class="loadingVitrin"> 
     <img src="http://photoblog.toorajam.com/photos/4cf85d53afc37de7e0cc9fa207c7b977.jpg" onload="$(this).fadeTo(500, 1);"> 
    </div> 
</div>​ 

CSS:

html, body { 
    padding: 10px; 
} 

.frame { 
    z-index: 15; 
    box-shadow: 0 0 10px gray; 
    width: 350px; 
    height: 350px; 
    border: gray solid 1px; 
    padding: 5px; 
    background: #F0F9FF; 
} 

.loadingVitrin { 
    z-index: 15; 
    width: 350px; 
    height: 350px; 
    overflow: hidden; 
    background: url("http://photoblog.toorajam.com/images/main/ajax-loader.gif") no-repeat center; 
} 

.loadingVitrin img { 
    display: none; 
    height: 350px; 
} 
​ 
0

Ho avuto lo stesso problema. nel tentativo di ottenere una risposta, ho raggiunto la tua domanda. In ogni modo il modo in cui sono riuscito a tipo di risolverlo era posizionando:

<div style="visibility:hidden; position:absolute; margin-left:-10000px;"> 
    <img src="foo.png" /> 
    // place all the images in here that you eventually will need 
</div> 

le immagini verranno scaricate in modo asincrono. se hai già un'immagine, questa non verrà più scaricata e verrà salvata nella cache del browser. quindi se l'utente trascorre 30 secondi nella prima pagina, l'intero sito sarà molto più veloce. beh dipende dalle dimensioni del tuo sito. ma questo risolve il problema quando si utilizza un sito Web di piccole dimensioni.

So che questa non è una soluzione reale Avrò una taglia sulla tua domanda.

2
success: function(xml) { 
    var img = $(xml).find('image[id=' + i + ']'), 
     id = img.attr('id'), 
     url = img.find('url').text(); 
    // hide loading 
    $('#loading'+i).hide(); 
    $('<img src="'+url+'" onLoad="loadImages('+i+')" />').load(function() { 
     // after image load 
     $('#loading' + i).html(this); // append to loading 
     $('#loading'+i).fadeIn(); // fadeIn loding 
    }); 
} 
0

Grazie a @thecodeparadox ho finito con:

$.get("SomePage.aspx", "", function (r) { 

    // r = response from server 

    // place response in a wrapper 
    var wrapper = $('<div id="wrapper" style=""></div>').html(r); 

    // need to write the images somewhere in the document for the event onload to fire 
    // loading content is a hidden div in my document. 
    $(document).append(wrapper); 
    //$("#LoadingContent").html("").append(wrapper); 

    var counter = 0; 

    var images = $(wrapper).find("img"); // get all the images from the response 

    // attach the onload event to all images 
    images.bind("load", function() { 

     counter++; 

     if (counter == images.size()) { // when all images are done loading 
      // we are now save to place content 
      // place custom code in here 
      // executeSomeFuction(); 
      $("#AjaxContent").html(r); 
      $(document).remove(wrapper); 
     } 
    }); 

}, "text"); 
0

Devi solo precaricare ogni immagine con l'oggetto Image(). Lo script che segue è piuttosto facile da usare. Basta scrivere nel "callbackFN()" qualunque codice tu voglia e poi "preload_images (array_img)". Più precisly:

var array_images = []; 
    $.ajax 
      ({ 
       type: "GET", 
       url: "sites.xml", 
       dataType: "xml", 
       async: "true", 
       success: function(xml) 
       { 
        var img = $(xml).find('image[id=' + i + ']'), 
        id = img.attr('id'), 
        url = img.find('url').text(); 
        array_images.push(url); 
       } 
      }); 




// Your callback function after loading: 
function callbackFN() { 
    // Do whatever you want HERE 
    // Pretty much this: 
    for (var i = 1; i<=array_images.length; i++) { 
     $('#loading'+i).html('<img src="'+url+'" />').hide(); 
     $('#loading'+i).fadeIn(); 
    } 
} 


var array_obj = Array(); 
var iKnowItsDone = false; 
// Timer (IE BULLET PROOF) 
var ieCheckImgTimer; 
     // Check if images are loaded 
    function images_complete(obj) { 
     var max = obj.length; 
     var canGo = true; 
     for (var i = 0; i<max; i++){ 
      if (!obj[i].complete) { 
       canGo = false; 
      } 
     } 
     return canGo; 
    } 
    // Loop to check the images 
    function preload_images(obj) { 
     var max = obj.length; 
     for (var i = 0; i<max; i++){ 
      var img = new Image(); 
      img.src = obj[i]; 
      array_obj.push(img); 

      img.onload = function() { 
       check_img(); 
      } 
     } 
     ieCheckImgTimer = setTimeout('check_img()',250); 
    } 

     // Timer to see if all the images are loaded yet. Waits till every img are loaded 
    function check_img() { 
     if (ieCheckImgTimer) { 
      clearTimeout(ieCheckImgTimer); 
     } 
     if (images_complete(array_obj) && !iKnowItsDone) { 
      iKnowItsDone = true; 
      callbackFN(); 
     } 
     else { 
      ieCheckImgTimer = setTimeout('check_img()',250); 
     } 
    } 
0

provate questo:

ThumbImage = document.createElement("img"); 
ThumbImage.src = URL; 

ThumbImage.onload = function(){ 
    //function After Finished Load      
} 
0

Si desidera assicurarsi che l'immagine viene caricata dal browser, vale a dire nella cache del browser, prima di aggiungerlo al documento:

// create an image element 
$('<img />') 
    // add a load event handler first 
    .load(function() { 
     // append the image to the document after it is loaded 
     $('#loading').append(this); 
    }) 
    // then assign the image src 
    .attr('src', url); 

Così, per il codice che vorrei fare:

$(window).load(function() { 
    var txt=""; 
    for(var d=0;d<100;d++) 
    { 
     txt=txt + "<li class='gif' id='loading"+d+"'></li>"; 

    } 
    document.getElementById('page-wrap').innerHTML=txt; 

    $('<img />') 
     .load(function() { 
      $('#loading0').append(this); 
      loadImages(0); 
     }) 
     .attr('src', 'images/0.jpg'); 
}); 
function loadImages(i){ 
    i++ 
    $.ajax 
    ({ 
     type: "GET", 
     url: "sites.xml", 
     dataType: "xml", 
     async: "true", 
     success: function(xml) 
     { 
      var img = $(xml).find('image[id=' + i + ']'), 
      id = img.attr('id'), 
      url = img.find('url').text(); 

      $('<img />') 
       .load(function() { 
        $('#loading' + i) 
         .append(this) 
         .hide() 
         .fadeIn(); 
        loadImages(i); 
       }) 
       .attr('src', url); 
     } 
    }); 
} 

Forse è solo il tuo codice di esempio, ma non vedo perché 0.jpg e sites.xml, o il resto delle immagini, non possono essere caricati allo stesso tempo:

$(window).load(function() { 
    var buf = [], d; 
    for (d = 0; d < 100; d++) { 
     buf.push('<li class="gif" id="loading' + d + '"></li>'); 
    } 
    $('#page-wrap').html(buf.join('')); 

    $('<img />') 
     .load(function() { 
      $('#loading0').append(this); 
     }) 
     .attr('src', 'images/0.jpg'); 

    $.ajax({ 
     type: 'GET', 
     url: 'sites.xml', 
     dataType: 'xml', 
     async: true, 
     success: function(xml) { 
      var img, id, url, i; 

      xml = $(xml); 

      for (i = 1; i < 100; i++) { 
       img = xml.find('image[id=' + i + ']'); 
       id = img.attr('id'); 
       url = img.find('url').text(); 

       $('<img />') 
        .load(function() { 
         $('#loading' + i) 
          .append(this) 
          .hide() 
          .fadeIn(); 
        }) 
        .attr('src', url); 
      } 
     } 
    }); 
}); 
Problemi correlati