簡體   English   中英

使用javascript(jquery)在后台異步加載圖片

[英]Asynchronous image loading in the background with javascript (jquery)

我有一個申請表,在左側顯示圖像,在右側顯示一些輸入文本。 用戶將必須填寫輸入文本,然后單擊“下一步”以顯示下一張圖像。 問題是圖像很大,加載時間很長,很費時間。

我想做的是,例如,當用戶開始從第一個圖像填充表單時,我想開始用ajax異步下載下一個圖像,當用戶完成對第一個圖像的處理時,下一個圖像將下載到客戶端,當用戶單擊下一步時,瀏覽器將顯示下一張圖像,依此類推。

我嘗試了這段代碼,但是它沒有按照我的解釋工作。 該頁面正在等待,直到兩個圖像都被加載,然后顯示第一個圖像,任何幫助將不勝感激:

HTML

<img id="currentImage" src="currentImage.png" onload="currentImageLoad()"></img>
<img id="nextImage" style="display: none;"></img>

使用Javascript

function currentImageLoad(){
    $('#nextImage').attr('src' , 'nextImage.png');
}

您可以使用jQuery揭幕插件延遲加載圖像。

http://luis-almeida.github.io/unveil/

javascript是同步的。 您可以延遲第二個圖像的加載以防止這種情況:

function currentImageLoad(){
    setTimeout(function() {
        $('#nextImage').attr('src' , 'nextImage.png');
    }, 10); // 10ms
}

這就是您所需要的,並不復雜。 JQuery僅在此處用於簡化選擇/ DOM操作。

<!-- click this button to append the image to #image-frame -->
<button id="append-image">append image</button>

<!-- image will go here -->
<div id="image-frame"></div>

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(){

    // 1. create a image object and load the image file (this will display nowhere)
    var image_url = 'https://image.spreadshirtmedia.net/image-server/v1/compositions/123658308/views/1,width=300,height=300,version=1472099537/evil-maenner-premium-t-shirt.jpg',
        image = new Image();
    image.src = image_url;

    // 2. create a new <img> element and append to the frame
    // (the image will load from cache if the previous download is finished, or load from remote if it's not)
    $('#append-image').on('click', function(e){
        e.preventDefault();
        $('<img src="'+image_url+'">').appendTo($('#image-frame'));
    });
});
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM