html5’s APIs include: 1. requestAnimationFrame; 2. Client storage; 3. History; 4. worker; 5. file Reader; 6. websocoket, etc.
The operating environment of this tutorial: Windows 7 system, HTML5 version, Dell G3 computer.
1. requestAnimationFrame (Request animation key frame)
1.1 requestAnimationFrame how to use?
Foreshadowing:
Let’s take a look at how we usually animate an element in JS.
We usually use timers to set the animation or displacement after a long time.
<style> .demo{ width: 100px; height:100px; background-color: red; position:absolute; left: 0; } </style> </head> <body> <div class="demo"></div> <script> var dom = document.getElementsByClassName('demo')[0]; items = setInterval(function(e){ dom.style.left = dom.offsetLeft + 50 +'px'; if(dom.offsetLeft == 500){ clearInterval(items); } },10); </script>
We can see that using JS timer You can achieve animation effects
However, the JS timer will have a shortcoming
The browser redraws every 1s -> 60 times, so It redraws approximately every 16ms
If we do the same thing as above, increase left50px every 10ms. The page will cause key frames to be lost
requestAnimationFrame: (after optimization)
<style> .demo { width: 100px; height: 100px; background-color: red; position: absolute; left: 0; } </style> </head> <body> <div class="demo"></div> <script> var dom = document.getElementsByClassName('demo')[0]; function move() { dom.style.left = dom.offsetLeft + 50 + 'px'; var items = requestAnimationFrame(move); if(dom.offsetLeft == 500){ cancelAnimationFrame(items); } } move(); </script>
1.2 What is the difference between requestAnimationFrame and setTImeout?
setTimeout executes the callback function after n milliseconds. In the callback function, setTimeout can be called recursively to implement animation.
.demo { width: 100px; height: 100px; background-color: red; position: absolute; left: 0; } </style> </head> <body> <div class="demo"></div> <script> var dom = document.getElementsByClassName('demo')[0]; function move() { var items = setTimeout(function () { dom.style.left = dom.offsetLeft + 50 + 'px'; if (dom.offsetLeft == 500) { clearTimeout(items); } else { move(); } }, 10) } move(); </script>
The biggest advantage of using requestAnimationFrame to execute animation is that it can ensure that the callback function is only executed once during each refresh interval of the screen, so that frames will not be lost and the animation will not be lost. There will be no lag.
.demo { width: 100px; height: 100px; background-color: red; position: absolute; left: 0; } </style> </head> <body> <div class="demo"></div> <script> var dom = document.getElementsByClassName('demo')[0]; function move() { var items = requestAnimationFrame(function () { dom.style.left = dom.offsetLeft + 50 + 'px'; if (dom.offsetLeft == 500) { cancelAnimationFrame(items); } else { move(); } }) } move(); </script>
##1.3 Advantages of requestAnimationFrame
2. Client Storage
2.1 Storage: Will not be transmitted to the server
2.1.1 How to use Storage Master method
存储信息到用户的设备上,数据量较小 4k
navigator.cookieEnabled 检查是否启用了cookie
三、历史记录
BOM中的 History对象方法
现在已知我有三个标签页(从红色小方块开始)
3.1history.length 长度
通过调用这个方法就可以知道,当前历史记录里面有几条数据(几个网页)
3.1history.back() 回退
当前位置在第三页(淘宝页面),回退一页就会跳转到第二页(百度页面)
3.2 history.forward() 前进
当前在红色小方块当前页,前进一页就会跳转至第二页(百度页面)
3.3 history.go(n) 跳转至指定页
当前在红色小方块页面即为第0页,go(2)就会跳转至第三页(淘宝页面)
当前在淘宝页面即为第三页,go(-2)就会跳转至第一页(红色方块页面)
HTML5中新增的方法 此方法受同源策略限制,需要在服务器下操作
1、pushState 添加一条历史记录
2、replaceState 替换当前的历史记录
1. popstate 监听页面历史记录一旦发生改变时触发
history.pushState(null, null, '#a'); window.addEventListener('popstate', function(e){ //监听 popstate事件 有没有发生改变 console.log("历史记录发生改变,我触发了"); }, false)
应用场景
多应用于搜索,后台管理系统,或者父子页面之间的切换(开发一个页面就够了)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> </style> </head> <body> <input type="text" id="inp"> <button id="btn">搜索</button> <ul id="wrapper"></ul> <script> var wrapper = document.getElementById('wrapper'); var inp = document.getElementById('inp'); var btn = document.getElementById('btn'); var data = [{ name: '科比' }, { name: '杜兰特' }, { name: '库里' }, { name: '哈登' }, { name: '詹姆斯' }, { name: '字母哥' }, { name: '杜兰特' }, { name: '科比' }, { name: '科比' }]; function radeDom(data) { var str = " "; for (var i = 0; i < data.length; i++) { str += "<li>" + data[i].name + "</li>"; } wrapper.innerHTML = str; } radeDom(data); btn.onclick = function () { var key = inp.value; var dataList = data.filter(function (item, index) { return item.name.indexOf(key) > -1; }) radeDom(dataList); history.pushState({ //点击后添加历史记录,key为当前的key key: key }, null, '#a'); } window.addEventListener('popstate', function (e) { //当历史记录事件改变时 var key = e.state ? e.state.key : ''; //判断当前页的key是否等于当前页的key var dataList = data.filter(function (item, index) { return item.name.indexOf(key) > -1; }); inp.value = key; //让输入框的value等于当前页的key radeDom(dataList); }, false) </script> </body> </html>
2. hashchange
用于监听hash值的改变触发事件,就是链接 # 这个东西的改变而触发
跟popstate的用法大同小异,都差不多。用途也都是一样的。所以大家可以自己试试
四、worker (受同源策略限制,需要在服务器下运行)
4.1 了解worker
worker字面意思是工人、雇佣员工的意思。
worker是一种异步执行JS的方式。
4.2 worker应用
var worker = new worker('worker.js'); // worker文件必须和主文件满足同源策略
就是在执行代码前雇佣一名工人(一个JS文件),把数据交给他让他异步执行,执行完了给主人返回回来。
主人可以在执行完代码后,调用解雇工人的方法,就不能继续传数据,
工人可以在执行完代码后,调用辞职方法,就不能继续传数据。
传输数据
postMessage 、onmessage
返回数据
4.3 结束worlker
4.4woker的缺点
(1)同源限制
分配给 Worker 线程运行的脚本文件,必须与主线程的脚本文件同源。
(2)DOM 限制
Worker 线程所在的全局对象,与主线程不一样,无法读取主线程所在网页的 DOM 对象,也无法使用document
、window
、parent
这些对象。但是,Worker 线程可以navigator
对象和location
对象。
(3)通信联系
Worker 线程和主线程不在同一个上下文环境,它们不能直接通信,必须通过消息完成。
(4)脚本限制
Worker 线程不能执行alert()
方法和confirm()
方法,但可以使用 XMLHttpRequest 对象发出 AJAX 请求。
(5)文件限制
Worker 线程无法读取本地文件,即不能打开本机的文件系统(file://
),它所加载的脚本,必须来自网络。
4.5 其他特性
4.6主要应用场景
Ajax轮询可以使用,每隔一段时间获取一下数据(用一个定时期每隔一段时间,向后端发送一次请求)
五、fileReader(上传文件,读取中的详细信息)
5.1 fileReader的使用方法
var reader = new FileReader();
按照不同项目的需求使用不同的方法,在这里我们就用这里面的readAsDataURL( )这个方法
我们先来看怎么读取文件,我们需要先把文件发送至服务器,等他给我返回文件的URL地址,然后我拿着URL地址来渲染我的页面
既然我们可以接收到返回的地址,那我们就可以把图片渲染到页面了
<style> .img{ height: 300px; } </style> </head> <body> <input type="file"> <img class="img lazy" src="/static/imghwm/default1.png" data-src="" alt=" alt="" > <script> var reader = new FileReader(); //创建FileReader(读文件对象) var inp = document.getElementsByTagName('input')[0]; var img = document.getElementsByClassName('img')[0]; inp.onchange = function(){ //onchange是当用户改变input输入框内容时执行一段JS代码时触发 console.log(inp.files); //flies 是你上传什么文件,他就会给你返回一个文件信息的伪数组 reader.readAsDataURL(inp.files[0]);//读取文件,伪数组中的第0项 } reader.onloadstart = function(e){ console.log('读取开始时触发', e); } reader.onprogress = function(e){ console.log('读取中', e); } reader.onloadend = function(e){ console.log('读取完成', e); } reader.onload = function(e){ console.log('文件读取成功', e); } reader.onabort = function(e){ console.log('中断时触发', e); } reader.onerror = function(e){ console.log('出错时触发', e); } </script>
<style> .img{ height: 300px; } </style> <input> <img class="img lazy" src="/static/imghwm/default1.png" data-src="" alt="What are the APIs of html5?" > <script> var reader = new FileReader(); //创建FileReader(读文件对象) var inp = document.getElementsByTagName('input')[0]; var img = document.getElementsByClassName('img')[0]; inp.onchange = function(){ //onchange是当用户改变input输入框内容时执行一段JS代码时触发 console.log(inp.files); //flies 是你上传什么文件,他就会给你返回一个文件信息的伪数组 reader.readAsDataURL(inp.files[0]);//读取文件,伪数组中的第0项 } reader.onloadstart = function(e){ console.log('读取开始时触发', e); } reader.onprogress = function(e){ console.log('读取中', e); } reader.onloadend = function(e){ console.log('读取完成', e); } reader.onload = function(e){ console.log('文件读取成功', e); img.src = e.target.result; } reader.onabort = function(e){ console.log('中断时触发', e); } reader.onerror = function(e){ console.log('出错时触发', e); } </script>
在文件读取中我们可以知道两个值 loaded、total
已知这两个值,我们就可以实现加载进度条了
<style> .img{ height: 300px; } .wrapper{ width: 300px; height: 30px; border: 1px solid black; } .wrapper .content{ width: 0; height: 30px; background-color:blue; overflow: hidden; } </style> <input> <img class="img lazy" src="/static/imghwm/default1.png" data-src="" alt="What are the APIs of html5?" > <div> <div></div> </div> <span></span> <script> var reader = new FileReader(); //创建FileReader(读文件对象) var inp = document.getElementsByTagName('input')[0]; var img = document.getElementsByClassName('img')[0]; var con = document.getElementsByClassName('content')[0]; var text = document.querySelector('.text'); inp.onchange = function(){ //onchange是当用户改变input输入框内容时执行一段JS代码时触发 console.log(inp.files); //flies 是你上传什么文件,他就会给你返回一个文件信息的伪数组 reader.readAsDataURL(inp.files[0]);//读取文件,伪数组中的第0项 } reader.onloadstart = function(e){ console.log('读取开始时触发', e); } reader.onprogress = function(e){ // console.log('读取中', e。loaded / e.total * 100%); var precent = e.loaded / e.total * 100; //当前读取的值除以文件总大小,乘以100%。在读取中会不断触发 var width = Math.round(300 * precent / 100); //进度条长度300乘以前面得到的值,除以100%,四舍五入取整 con.style.width = width + 'px'; //把值赋给宽度 text.innerHTML = Math.round(precent) + '%'; //把读取中的值取整把数字赋给文字进度条 } reader.onloadend = function(e){ console.log('读取完成', e); } reader.onload = function(e){ console.log('文件读取成功', e); img.src = e.target.result; } reader.onabort = function(e){ console.log('中断时触发', e); } reader.onerror = function(e){ console.log('出错时触发', e); } </script>
然后我们还可以添加终止读取,就是在文件上传的中途,停止上传
只需要添加一个按钮,和一个点击事件
btn.onclick = function () { reader.abort(); console.log('终止'); }
5.2 fileReader 可实现的功能
图片预览、异步向发送服务端发送请求
六、websocket(不受同源策略限制)
websocket是一种网络协议,是在HTTP基础上做了一些优化的协议,与HTTP无直接关系。
6.1 简单回忆HTTP协议
6.2为什么有HTTP还需要websocket呢?
因为HTTP协议有一个缺陷:通信只能由客户端发起
服务器端不能实时的发送最新数据给客户端,
我想要最新的数据怎么办呢? 只能用Ajax轮询(开启一个定时器,每隔一段时间调用请求一次数据)
然而websocket呢只需要发送一次请求,只要服务器有最新数据就会自动给你发送过来,不用再次请求
比如现在做的是一个天气状况的项目,每当天气有变化就会自动更新最新天气状况了
6.3 websocket的特点
6.4 websocket事件
6.5 创建websocket
ws://echo.websocket.org/ 是用来测试的地址
var socket = new WebSocket('ws://echo.websocket.org/');
调用e.data就可以打印出来数据了
我们再来看看close这个方法
6.6 websocket属性
6.7 websocket的优点
客户端与服务器都可以主动传送数据给对方;
不用频率创建TCP请求及销毁请求,减少网络带宽资源的占用,同时也节省服务器资源;
可以只请求一次,就会自动更新返回
推荐教程:《html视频教程》
The above is the detailed content of What are the APIs of html5?. For more information, please follow other related articles on the PHP Chinese website!

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability


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

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

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