


I see some large websites. If the page has many pictures, when you scroll to the corresponding row, the pictures in the current row are loaded immediately. In this way, the page opens with only the pictures in the visible area, and Other hidden pictures will not be loaded, which will speed up page loading. For longer pages, this solution is better. The principle is this: the images below the visible area of the page are not loaded until the user scrolls down to the image location, and then loaded. What are the benefits of doing this? ——When the page has several screens of content, it is possible that the user will only view the content of the first few screens. In this way, we can only load the images that the user needs to see and reduce the load caused by the server sending image files to the user's browser. Here are three steps: This method introduces to you js to implement delayed loading of images.
JS implementation of delayed image loading method 1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>lazyImage2.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css" mce_href="styles.css">--> </head> <body style="text-align:center" mce_style="text-align:center"> <p> </p><p> </p><p> </p><p> </p><p> </p> <div style="height:1290px;width:800px;border:1px;background:gray;"></div> <div style="height:150px;width:800px;border:1px;background:green;"></div> <img class="lazy lazy" src="/static/imghwm/default1.png" data-src="images/sprite.gif" mce_ alt="images/lazyloadImg.jpg" /> <script type="text/javascript"><!-- var temp = -1;//用来判断是否是向下滚动(向上滚动就不需要判断延迟加载图片了) window.onscroll = function() { var imgElements = document.getElementsByTagName("img"); var lazyImgArr = new Array(); var j = 0; for(var i=0; i<img src="/static/imghwm/default1.png" data-src="图片路径" class="lazy" Elements.length; i++) { if(imgElements[i].className == "lazy"){ lazyImgArr[j++] = imgElements[i]; } } var scrollHeight = document.body.scrollTop;//滚动的高度 var bodyHeight = document.body.offsetHeight;//body(页面)可见区域的总高度 if(temp < scrollHeight) {//为true表示是向下滚动,否则是向上滚动,不需要执行动作。 for(var k=0; k<lazyImgArr.length; k++) { var imgTop = lazyImgArr[k].offsetTop;//1305(图片纵坐标) if((imgTop - scrollHeight) <= bodyHeight) { lazyImgArr[k].src = lazyImgArr[k].alt; lazyImgArr[k].className = "notlazy" } } temp = scrollHeight; } }; // --></script> </body> </html>
JS method to implement delayed loading of web page images:
Before I post the code, let me tell you the principle of js to implement delayed loading of images.
Implementation principle:
Change all images that need delayed loading to the following format:
<img src="/static/imghwm/default1.png" data-src="图片路径" class="lazy" lazy_ border="0"/ alt="Summary of methods to implement lazy loading of images in javascript (three methods)_javascript skills" >
Then when the page loads, save all the images using lazy_src into an array, then calculate the top of the visible area when scrolling, and then make the top of the delayed-loaded images smaller than the current visible area (i.e. the image The src value of the image appearing in the visible area is replaced with lazy_src (load the image):
JS code:
lazyLoad = (function() { var map_element = {}; var element_obj = []; var download_count = 0; var last_offset = -1; var doc_body; var doc_element; var lazy_load_tag; function initVar(tags) { doc_body = document.body; doc_element = document.compatMode == 'BackCompat' ? doc_body : document.documentElement; lazy_load_tag = tags || ["img", "iframe"]; }; function initElementMap() { var all_element = []; //从所有相关元素中找出需要延时加载的元素 for (var i = 0, len = lazy_load_tag.length; i < len; i++) { var el = document.getElementsByTagName(lazy_load_tag[i]); for (var j = 0, len2 = el.length; j < len2; j++) { if (typeof (el[j]) == "object" && el[j].getAttribute("lazy_src")) { element_obj.push(all_element[key]); } } } for (var i = 0, len = element_obj.length; i < len; i++) { var o_img = element_obj[i]; var t_index = getAbsoluteTop(o_img); //得到图片相对document的距上距离 if (map_element[t_index]) { map_element[t_index].push(i); } else { //按距上距离保存一个队列 var t_array = []; t_array[0] = i; map_element[t_index] = t_array; download_count++; //需要延时加载的图片数量 } } }; function initDownloadListen() { if (!download_count) return; var offset = (window.MessageEvent && !document.getBoxObjectFor) ? doc_body.scrollTop : doc_element.scrollTop; //可视化区域的offtset=document的高+ var visio_offset = offset + doc_element.clientHeight; if (last_offset == visio_offset) { setTimeout(initDownloadListen, 200); return; } last_offset = visio_offset; var visio_height = doc_element.clientHeight; var img_show_height = visio_height + offset; for (var key in map_element) { if (img_show_height > key) { var t_o = map_element[key]; var img_vl = t_o.length; for (var l = 0; l < img_vl; l++) { element_obj[t_o[l]].src = element_obj[t_o[l]].getAttribute("lazy_src"); } delete map_element[key]; download_count--; } } setTimeout(initDownloadListen, 200); }; function getAbsoluteTop(element) { if (arguments.length != 1 || element == null) { return null; } var offsetTop = element.offsetTop; while (element = element.offsetParent) { offsetTop += element.offsetTop; } return offsetTop; } function init(tags) { initVar(tags); initElementMap(); initDownloadListen(); }; return { init: init } })();
How to use: Change the src of the image that needs to be delayed loaded on the page to lazy_src, then put the above js at the end of the body, and then call: lazyLoad.init();
To tease, you can use firebug to check whether the image is delayed loading.
Also:
If there is a column with content switching on your page, the images in the content may not be displayed when switching. The solution is to load the images separately during the content, such as:
///切换内容的代码… chlid.find("img[init_src]").each(function(){ $(this).attr("src",$(this).attr("init_src")); $(this).removeAttr("init_src"); });
Original js implementation of image delayed loading method three:
<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>通过原生js延迟加载图片</title> <style type="text/css"> div{width:100px;height:100px;background:#F00;margin-bottom:30px} </style> </head> <body> <div><img src="/static/imghwm/default1.png" data-src="a.gif" class="lazy" data-url="http://www.pokemon.name/w/image/Sprites/PDW/001.png " /></div> <div><img src="/static/imghwm/default1.png" data-src="a.gif" class="lazy" data-url="http://www.pokemon.name/w/image/Sprites/PDW/002.png " /></div> <div><img src="/static/imghwm/default1.png" data-src="a.gif" class="lazy" data-url="http://www.pokemon.name/w/image/Sprites/PDW/003.png " /></div> <div><img src="/static/imghwm/default1.png" data-src="a.gif" class="lazy" data-url="http://www.pokemon.name/w/image/Sprites/PDW/004.png " /></div> </body> //以上图片测试时可用复制多点 <script type="text/javascript"> (function(){ //common function tagName(tagName){ return document.getElementsByTagName(tagName); } function $(id){ return document.getElementById(id); } function addEvent(obj,type,func){ if(obj.addEventListener){ obj.addEventListener(type,func,false); }else if(obj.attachEvent){ obj.attachEvent('on'+type,func); } } //这里可以按照需要配置些参数 var v={ eleGroup:null, eleTop:null, eleHeight:null, screenHeight:null, visibleHeight:null, scrollHeight:null, scrolloverHeight:null, limitHeight:null } //对数据进行初始化 function init(element){ v.eleGroup=tagName(element) screenHeight=document.documentElement.clientHeight; scrolloverHeight=document.body.scrollTop; for(var i=0,j=v.eleGroup.length;i<j;i++){ if(v.eleGroup[i].offsetTop<=screenHeight && v.eleGroup[i].getAttribute('data-url')){ v.eleGroup[i].setAttribute('src',v.eleGroup[i].getAttribute('data-url')); v.eleGroup[i].removeAttribute('data-url') } } } function lazyLoad(){ if(document.body.scrollTop == 0){ limitHeight=document.documentElement.scrollTop+document.documentElement.clientHeight; }else{ limitHeight=document.body.scrollTop+document.documentElement.clientHeight; } for(var i=0,j=v.eleGroup.length;i<j;i++){ if(v.eleGroup[i].offsetTop<=limitHeight && v.eleGroup[i].getAttribute('data-url')){ v.eleGroup[i].src=v.eleGroup[i].getAttribute('data-url'); v.eleGroup[i].removeAttribute('data-url') } } } init('img') addEvent(window,'scroll',lazyLoad); })() </script> </html>
The above content introduces js to implement delayed loading of images through three methods. I hope you like it.

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
