Javascript + HTML - 在后台加载图像(异步?)

Mar*_*wed 5 html javascript asynchronous image loading

我发现了许多描述 javascript 图像加载的主题,但并不完全是我要搜索的主题。

我目前正在以正常方式加载 html 中的图像,例如

<img src="images/big-image.jpg">
Run Code Online (Sandbox Code Playgroud)

这会导致网页上的空白空间从上到下填充了加载图像。此外,我总是要注意图像的文件大小。

什么我要实现的是,在页面加载时,每幅图像(约10KB)的缩小的版本显示。当页面完全加载时,应该有一个 javascript 函数在后台加载大图像并在加载时替换它们。

我已经找到了一种使用 javascript 执行此操作的方法,但是在替换所有图像之前,浏览器会显示他处于“加载”状态。是否可以使用异步方法在后台执行加载任务?

<img src="small.jpg" id="image">

<script>
        <!--
            var img = new Image(); 
            img.onload = function() { 
               change_image(); 
            } 
            img.src = "small.jpg";  

            function change_image() {
                document.getElementById("image").src = "big.jpg";
            }
        //-->
</script>
Run Code Online (Sandbox Code Playgroud)

Ale*_*x W 4

你试过这个吗?

window.onload = function() {
    setTimeout(function() {
        // XHR to request a JS and a CSS
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://domain.tld/preload.js');
        xhr.send('');
        xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://domain.tld/preload.css');
        xhr.send('');
        // preload image
        new Image().src = "http://domain.tld/preload.png";
    }, 1000);
};
Run Code Online (Sandbox Code Playgroud)

http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/