Home >Web Front-end >JS Tutorial >Implementation method of asynchronously loading images through js

Implementation method of asynchronously loading images through js

小云云
小云云Original
2018-03-17 16:47:313159browse

This article mainly shares with you the implementation method of asynchronous loading of images through js. Mainly considering the limitations of the network, for a better user experience, the asynchronous loading and display method is used to load images for img, and the code is directly pasted:

Tag:
<img onload="getHead(this,url);" src="../../static/xxx/xxx/head.png" >
<%--这里注意1,src写在 onload后面2,请给src一个默认的图片路径,不能直接src=""--%>

js:

function getHead(obj,portraitUrl){
    //模拟网络延迟请求
     setTimeout(function (){   
     obj.src=../../static/xxx/xxx/add.png;               
    },1000+Math.random()*5000);

   /*
    $.ajax({        type: "get",
        url: portraitUrl,
        async: true,
        success: function (portrait) {
           obj.src=portrait;
            portraitUrl.onload=null;//这里每次给obj的src赋值后都会执行onload 为了避免无限死循环需要这样置空
        }
*/
}

And the above are all the sequelae of writing too much for Android. There is no need to be so troublesome. I am crazy and write ajax myself. Please see all below:

<img src="http:/xxxx.png" onerror=&#39;this.src="../../static/xxx/xxx/head.png" />//这就ok了
Mainly considering network limitations, for a better user experience, the asynchronous loading and display method is used to load images for img, and directly paste the code:
Tag:
<img onload="getHead(this,url);" src="../../static/xxx/xxx/head.png" >
<%--这里注意1,src写在 onload后面2,请给src一个默认的图片路径,不能直接src=""--%>

js:

function getHead(obj,portraitUrl){
    //模拟网络延迟请求
     setTimeout(function (){   
     obj.src=../../static/xxx/xxx/add.png;               
    },1000+Math.random()*5000);

   /*
    $.ajax({        type: "get",
        url: portraitUrl,
        async: true,
        success: function (portrait) {
           obj.src=portrait;
            portraitUrl.onload=null;//这里每次给obj的src赋值后都会执行onload 为了避免无限死循环需要这样置空
        }
*/
}

And the above are all the sequelae of writing too much for Android. There is no need to go to such trouble. I'm crazy and write an ajax myself. Please see below for all:

<img src="http:/xxxx.png" onerror=&#39;this.src="../../static/xxx/xxx/head.png" />//这就ok了

Related recommendations:

js implements image preloading (js operates Image object attribute complete, event onload asynchronously loads images)_javascript skills

The above is the detailed content of Implementation method of asynchronously loading images through js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn