2014-12-13 4 views
2

이제는 2 년 동안 stackoverflow를 읽었지 만 게시 된 적이 없습니다. 오늘까지 - 나 혼자서 해결할 수 없었던 문제로 달려 들었고 해결책을 찾지 못했습니다.이미지를 서버에서 생성해야 할 때 이미지를 브라우저 캐시에 비동기 적으로 미리로드합니다.

시나리오 : 기본적으로 웹 사이트의 스크린 샷을 보여주는 동적 웹 페이지가 있습니다. 이 스크린 샷은 새로운 사용자가있을 때마다 생성되며 URL이 변경됩니다. 이 이미지를 브라우저 캐시에 미리로드하여 사용자가 링크를 클릭하면 0ms 이내에 사용할 수있게하려고합니다. 페이지의 주관적인로드 시간이 늘어나는 것을 원하지 않기 때문에 백그라운드에서 눈에 보이지 않게로드되어야합니다.

내 접근 방식 : 나중에 규모를 조정할 수있는 인프라로 jelastic을 사용한 다음 nginx, PHP 및 PhantomJS를 사용하여 centOS를 설치했습니다. 나는 스크린 샷 만들기 위해 phantomJS를 조회 할 수 PHP를 사용

간부 (. "phantomjs engine.js"$ 소스를 ">을/dev/null &". "$ filez을..")

dev/null은 사용자 로딩 시간을 늘리지 않기 위해 사용됩니다. 브라우저에 대한 링크를 출력합니다. 지금까지는 작동합니다. 지금은 이러한 이미지를 미리로드하려면 : 나는 proably 여기에 잘못했던

for (var i = 0; i < document.links.length; i++) { 
    imgArray[i] = new Image(1,1); 
    imgArray[i].visibility = 'hidden'; 
    imgArray[i].src = (document.links[i].href.substr(7) + ".png");    
    document.links[i].href = 'javascript: showtouser("' + imgArray[i].src.substr(7) + '");'; 
} 

두 가지 : 이미지가 서버에서 생성되기 전에

  • 내가 이미지 미리로드를 시작합니다. 이미지가 phantomJS에 의해 생성 된 후에 캐싱을 시작하는 방법을 찾지 못했습니다. Onload 이벤트는 분명히 여기서 작동하지 않습니다.
  • 나는 나의 접근 방식은 정말 비동기 아니라고 생각과는 사용자 내가 잘못 뭐하는 거지

느끼는 주관적인 로딩 시간을 증가시킬 것인가? 나는 ISP 사람, 나는 자바 스크립트 빨아 :/

답변

0

당신은 비동기했다. 필요한 것은로드되지 않은 이미지를 식별하고 다시 시도하는 메커니즘이었습니다.

실패하면 다시 시도 및 시도 했음에도 존재하지 않는 이미지의 링크를 숨기 이미지를 미리로드 할이 스크립트 (demo) :

var links = Array.prototype.slice.call(document.links, 0); // Converting links to a normal array 

links.forEach(prepareImageLink); 

function prepareImageLink(link) { 
    var retries = 3; // current image number of retries 
    var image = new Image(); 

    /** option: hide all links then reveal those with preloaded image 
    link.style.visibility = 'hidden'; 

    image.onload = function() { 
     link.style.visibility = ''; 
    }; 
    **/ 

    image.onerror = function() { 
     if(retries === 0) { 
      link.style.visibility = 'hidden'; // hide the link if image doesn't exist 
      //link.remove(); // option - remove the link if image doesn't exist 
      return; 
     } 

     retries--; 

     setTimeout(function() { 
      image.src = image.src + '?' + Date.now(); // for image to reload by adding the current dateTime to url 
     }, 1000); // the amount of time to wait before retry, change it to fit you're system 

    }; 

    image.src = (link.href + ".png"); // add .substr(7) in your case 

    /** This is instead of 'javascript: showtouser("' + imgArray[i].src.substr(7) + '");'; which won't work on some browsers **/ 

    link.addEventListener('mouseover', function() { 
     document.getElementById('image').src = image.src; // change to your showtouser func 
    }); 
}