search
HomeWeb Front-endJS TutorialHow to implement delayed loading of images using dataset

下面小编就为大家分享一篇基于dataset的使用和图片延时加载的实现方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

首先,先介绍一下关于javascript中dataset属性。。

html5中可以使用data-前缀设置我们需要的自定义属性,来进行一些数据的存放。

下面是元素应用data属性的一个例子:

<p id="day-meal-expense" data-drink="tea" data-food="noodle" data-meal="lunch">$18.3</p>

要想获取某个属性的值,可以像下面这样使用dataset对象:

var expenseday=document.getElementById(&#39;day-meal-expense&#39;);
 var typeOfDrink=expenseday.dataset.drink;
 console.log(typeOfDrink);//tea
 console.log(expenseday.dataset.food);//noodle
 console.log(expenseday.dataset.meal);//lunch

如果浏览器支持dataset,则会弹出注释内容,如果浏览器不支持dataset则会报错,无法获取属性drink/food/meal的值:对象为null或未定义(如IE9版本).

data属性基本上所有的浏览器都是支持的,但是dataset对象支持的就比较特殊了,目前仅在Opera 11.1+,Chrome 9+下可以通过javascript,使用dataset访问你自定义的data属性.至于其他浏览器,FireFox 6+(未出)以及Safari 6+(未出)会支持dataset对象,至于IE浏览器,目前看来还是遥遥无期的趋势.

问:不是有getAttribute来获取自定义属性么。要这个干嘛??

答:如果使用传统的方法获取属性值应该会类似下面:

var typeOfDrink=document.getElementById(&#39;day-meal-expense&#39;).getAttribute(&#39;data-drink&#39;);

现在,如果我们要获得多个自定义的属性值,就要用下面N行代码来实现了:

var attrs=expenseday.attributes, expense={},i,j;
for (i=0,j=attrs.length;i<j;i++){
 if(attrs[i].name.substring(0,5)==&#39;data-&#39;){
 expense[attrs[i].name.substring(5)]=attrs[i].value;
 }
}

而使用dataset属性,我们根本不需要任何循环去获取你想要的那个值,直接秒杀:

expense=document.getElementById(&#39;day-meal-expense&#39;).dataset;

问:怎么操作这玩意~

答:可以像下面这样操作名-值对:

charInput=[];
 for(var item in expenseday){
 charInput.push(expenseday[item]);
 }

让所有的自定义属性塞到一个数组中.

如果你想删除一个data属性,可以这么做:

delete expenseday.dataset.meal;
console.log(expenseday.dataset.meal)//undefined

如果你想给元素添加一个属性,可以这么做:

expenseday.dataset.dessert=&#39;icecream&#39;;
console.log(expenseday.dataset.dessert);//icecream

dataset并不是典型意义上的JavaScript对象,而是个DOMStringMap对象,DOMStringMap是HTML5一种新的含有多个名-值对的交互变量.

下面来个实际的应用吧~

(当然图片地址肯定是空的。想要看效果的自己去加个图片地址,这个效果附上图片也是看不出什么所以就不上截图了)

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>图片延迟加载</title>
 <style>
 #box{
  width: 100%;
  height: 500px;
 }
 #box img{
  width: 100%;
  height: 500px;
  transition: 1s;
  opacity: 0;
 }
 </style>

</head>
<body>
 <p id="box"></p>
 <script type="text/javascript">
 var data=["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"]
 var box=document.getElementById(&#39;box&#39;);
 // var img=document.createElement(img);
 for (var i = 0; i < data.length; i++) {
  var img=document.createElement(&#39;img&#39;);
  img.dataset.src=data[i];
  // img.style.opacity=1;
  box.appendChild(img);
  // console.log(box);
 }
 var imgs=document.querySelectorAll(&#39;img&#39;);
 window.addEventListener(&#39;scroll&#39;,loadFn);
 window.addEventListener(&#39;load&#39;,loadFn);
 function loadFn(){
  for (var i = 0; i < imgs.length; i++) {
  if(imgs[i].getBoundingClientRect().top<window.innerHeight){
   if(imgs[i].dataset.src){
   imgs[i].src=imgs[i].dataset.src;
   imgs[i].style.opacity=1;
   imgs[i].removeAttribute(&#39;src&#39;);
   }
  }
  }
 }
 </script>
</body>
</html>

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在angularjs中如何实现柱状图动态加载

使用js如何实现时间戳与日期格式之间转换

在Vue中有关响应式原理(详细教程)

The above is the detailed content of How to implement delayed loading of images using dataset. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools