[英]Preload images asynchronously into the browser cache when the image has to be generated on the server first
幾年來一直在閱讀stackoverflow,但從未發布過。 直到今天-遇到了一個我自己無法解決且找不到解決方案的問題。
場景:我有一個動態網頁,基本上顯示了網站的屏幕截圖。 這些屏幕截圖是為每個新用戶即時生成的,其URL也會更改。 我想將這些圖像預加載到瀏覽器緩存中,以便在用戶單擊鏈接后的0ms內可用。 我不想增加頁面的主觀加載時間,因此必須在后台將它們隱式加載。
我的方法:我使用jelastic作為我的基礎架構,以便以后進行擴展,然后使用nginx,PHP和PhantomJS安裝centOS。 我使用PHP查詢phantomJS來制作屏幕截圖:
exec(“ phantomjs engine.js”。$ source。“”。$ filez。“> / dev / null&”);
dev / null用於不增加對用戶的加載時間。 我將鏈接輸出到瀏覽器。 到目前為止,它仍然有效。 現在我要預加載這些圖像:
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) + '");';
}
我可能在這里做錯了兩件事:
我究竟做錯了什么? 我是ISP的家伙,我很爛javascript:/
您的方法是異步的。 您需要一種機制來識別未加載的圖像,然后重試。
此腳本將預加載圖像,如果失敗,則重試,並隱藏即使重試后也不存在的圖像鏈接( 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
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.