In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces what api is in html5, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.
The api of html5 are: 1, requestAnimationFrame;2, client storage; 3, history (History); 4, worker;5, file Reader;6, websocoket and so on.
The operating environment of this tutorial: windows7 system, HTML5 version, Dell G3 computer.
1. RequestAnimationFrame (request animation Keyframe)
1.1 how do I use requestAnimationFrame?
Lay the groundwork:
Let's take a look at how we animate an element in JS.
We usually use timers to set what animation or displacement will happen after how long.
.demo {width: 100px; height:100px; background-color: red; position:absolute; left: 0;} var dom = document.getElementsByClassName ('demo') [0]; items = setInterval (function (e) {dom.style.left = dom.offsetLeft + 50 +' px'; if (dom.offsetLeft = 500) {clearInterval (items)) }, 10)
As we can see, animation can be achieved with JS timers.
However, JS timers have a drawback
The browser is redrawn every 1s-"60 times, so redraw for 16ms is about once.
If we add left50px every 10ms, as we did above. The page will cause keyframes to be lost.
RequestAnimationFrame: (after optimization)
.demo {width: 100px; height: 100px; background-color: red; position: absolute; left: 0;} 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 ()
1.2 what is the difference between requestAnimationFrame and setTImeout?
SetTimeout executes the callback function after n milliseconds, and setTimeout can be called recursively in the callback function to realize animation.
.demo {width: 100px; height: 100px; background-color: red; position: absolute; left: 0;} 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 ()
The biggest advantage of using requestAnimationFrame to perform animation is to ensure that the callback function is executed only once during each refresh interval on the screen, so that frames are not lost and the animation does not stutter.
.demo {width: 100px; height: 100px; background-color: red; position: absolute; left: 0;} 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 ()
1.3 benefits of requestAnimationFrame
II. Client storage
2.1 Storage: will not be transferred to the server
2.1.1 how to use mastery methods for Storage
Storage object:
Take out the object:
Save array:
Fetch the array:
Common application of API localstorage sessionStorage
Set, get
Remove attributes (specify individual attributes)
Clear all set properties
2.1.2 localstorage sessionStorage cookie distinction
Localstorage:
Store information on the user's device, usually 5MB
Permanent storage unless manually cleared
Will be stored in the same domain
SessionStorage:
Store information on the user's device, usually 5MB
Temporary storage, the page will be cleared when closed.
Will not be stored in the same domain
Cookie:
Store information on the user's device with a small amount of data of 4k
Navigator.cookieEnabled checks if cookie is enabled
III. Historical records
History object method in BOM
It is now known that I have three tabs (starting with a small red square)
3.1history.length length
By calling this method, you can know how many pieces of data (several web pages) are in the current history.
3.1history.back () fallback
The current location is on the third page (Taobao page). If you roll back one page, you will jump to the second page (Baidu page)
3.2 history.forward () forward
Currently on the current page of the red square, one page forward will jump to the second page (Baidu page)
3.3 history.go (n) Jump to the specified page
Go (2) will jump to page 3 (Taobao page) when page 0 is the red square page.
Currently on Taobao page is the third page, go (- 2) will jump to the first page (red square page)
New method in HTML5 this method is restricted by the same origin policy and needs to be operated under the server
1. PushState adds a history record
2. ReplaceState replaces the current history
1. Triggered when the history of popstate snooping page changes
History.pushState (null, null,'# a'); window.addEventListener ('popstate', function (e) {/ / monitor whether the popstate event has changed console.log ("History changed, I triggered");}, false)
Application scenario
It is mostly used in search, background management system, or switching between parent and child pages (developing one page is enough)
Document search var wrapper = document.getElementById ('wrapper'); var inp = document.getElementById (' inp'); var btn = document.getElementById ('btn') Var data = [{name: 'Kobe'}, {name: 'Durant'}, {name: 'Curry'}, {name: 'Harden'}, {name: 'James'} {name: 'letter Brother'}, {name: 'Durant'}, {name: 'Kobe'}, {name: 'Kobe'}] Function radeDom (data) {var str = ""; for (var I = 0; I
< data.length; i++) { str += "" + data[i].name + ""; } wrapper[xss_clean] = 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 ({/ / add history after clicking. Key is the current key key: key}, null,'# a') } window.addEventListener ('popstate', function (e) {/ / when the history event changes, var key = e.state? E.state.key:''; / / determine whether the key of the current page is equal to the key var dataList of the current page = data.filter (function (item, index) {return item.name.indexOf (key) >-1;}); inp.value = key; / / make the value of the input box equal to the key radeDom (dataList) of the current page;}, false)
2. Hashchange
The change trigger event used to listen for the hash value is triggered by the change of the link #
The usage is more or less the same as that of popstate. It's all for the same purpose. So you can try it for yourself.
4. Worker (limited by the same origin policy, you need to run under the server)
4.1 learn about worker
Worker literally means workers and employees.
Worker is a way to execute JS asynchronously.
4.2 worker applications
Var worker = new worker ('worker.js'); / / the worker file must meet the same origin policy as the master file
Is to hire a worker (a JS file) before executing the code, give him the data to execute asynchronously, and return it to the owner after execution.
The owner can call the method of firing the worker after the code has been executed, so he cannot continue to pass the data.
The worker can call the resignation method after the code has been executed, and the data cannot be passed on.
Transmit data
PostMessage 、 onmessage
Return data
4.3 end worlker
Shortcomings of 4.4woker
(1) homology restriction
The script file assigned to the Worker thread to run must be of the same origin as the script file of the main thread.
(2) DOM restriction
The global object where the Worker thread is located, unlike the main thread, cannot read the DOM object of the web page where the main thread is located, and cannot use objects such as document, window, and parent. However, Worker threads can navigator objects and location objects.
(3) Communication
The Worker thread and the main thread are not in the same context. They cannot communicate directly and must be done through messages.
(4) script restrictions
The Worker thread cannot execute the alert () method and the confirm () method, but can use the XMLHttpRequest object to make an AJAX request.
(5) document restrictions
The Worker thread cannot read the local file, that is, it cannot open the local file system (file://). The script it loads must come from the network.
4.5 other Features
4.6 main application scenarios
Ajax polling can be used to get data at regular intervals (send a request to the backend at regular intervals with a fixed period of time)
5. FileReader (upload files and read details)
5.1 how to use fileReader
Var reader = new FileReader ()
Different methods are used according to the requirements of different projects, so here we will use the readAsDataURL () method.
Let's first look at how to read the file. We need to send the file to the server first, wait for him to give me the URL address of the file, and then I render my page with the URL address.
Now that we can receive the returned address, we can render the picture to the page.
.img {height: 300px;}
Var reader = new FileReader (); / / create FileReader (read file object) var inp = document.getElementsByTagName ('input') [0]; var img = document.getElementsByClassName (' img') [0]; inp.onchange = function () {/ / onchange triggers console.log (inp.files) when the user changes the contents of the JS input box / / flies will return a pseudo array of file information reader.readAsDataURL (inp.files [0]) to you if you upload the file; / / read the file, item 0 in the pseudo array} reader.onloadstart = function (e) {console.log ('triggered when reading starts', e);} reader.onprogress = function (e) {console.log ('reading', e) } reader.onloadend = function (e) {console.log ('read completed', e);} reader.onload = function (e) {console.log ('file read successfully', e);} reader.onabort = function (e) {console.log ('triggered on interrupt', e);} reader.onerror = function (e) {console.log ('triggered on error', e) }
.img {height: 300px;}
Var reader = new FileReader (); / / create FileReader (read file object) var inp = document.getElementsByTagName ('input') [0]; var img = document.getElementsByClassName (' img') [0]; inp.onchange = function () {/ / onchange triggers console.log (inp.files) when the user changes the contents of the JS input box / / flies will return a pseudo array of file information reader.readAsDataURL (inp.files [0]) to you if you upload the file; / / read the file, item 0 in the pseudo array} reader.onloadstart = function (e) {console.log ('triggered when reading starts', e);} reader.onprogress = function (e) {console.log ('reading', e) } reader.onloadend = function (e) {console.log ('read completed', e);} reader.onload = function (e) {console.log ('file read successfully', e); img.src = e.target.result;} reader.onabort = function (e) {console.log ('triggered on interrupt', e) } reader.onerror = function (e) {console.log ('trigger on error', e);}
We can know two values loaded and total in the file reading.
Knowing these two values, we can load the progress bar.
.img {height: 300px;} .wrapper {width: 300px; height: 30px; border: 1px solid black;} .wrapper .content {width: 0; height: 30px; background-color:blue; overflow: hidden;}
Var reader = new FileReader (); / / create FileReader (read file object) 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 triggers console.log (inp.files) when the user executes a piece of JS code when the user changes the contents of the input input box; / / flies is what file you upload, he will return you a pseudo array of file information reader.readAsDataURL (inp.files [0]) / / read the file, item 0 in the pseudo array} reader.onloadstart = function (e) {console.log ('triggered when reading starts', e);} reader.onprogress = function (e) {/ / console.log ('reading', e). Loaded / e.total * 100); var precent = e.loaded / e.total * 100; / / the value currently read is divided by the total file size, multiplied by 100%. During the read, var width = Math.round (300 * precent / 100) is constantly triggered; / / the progress bar length is multiplied by the previous value, divided by 100%, rounding con.style.width = width + 'px'; / / assigning the value to the width text[ XSS _ clean] = Math.round (precent) +'%' / / assign the whole number of values in reading to the text progress bar} reader.onloadend = function (e) {console.log ('read complete', e);} reader.onload = function (e) {console.log ('file read successfully', e); img.src = e.target.result } reader.onabort = function (e) {console.log ('trigger on interrupt', e);} reader.onerror = function (e) {console.log ('trigger on error', e);}
Then we can also add stop reading, that is, in the middle of file upload, stop uploading.
Just add a button and a click event
Btn.onclick = function () {reader.abort (); console.log ('terminate');}
5.2 functions that can be achieved by fileReader
Picture preview, asynchronously send a request to the sending server
6. Websocket (not restricted by the same origin policy)
Websocket is a kind of network protocol, which is optimized on the basis of HTTP and has no direct relationship with HTTP.
6.1simply recall the HTTP protocol
6.2. why do you need websocket when you have HTTP?
Because the HTTP protocol has a flaw: communication can only be initiated by the client.
The server cannot send the latest data to the client in real time.
What if I want the latest data? You can only use Ajax polling (start a timer and call for data at regular intervals)
However, websocket only needs to send a request once. As long as the server has the latest data, it will automatically send it to you. There is no need to request it again.
For example, what we are doing now is a project on weather conditions, which automatically updates the latest weather conditions whenever the weather changes.
6.3Features of websocket
6.4 websocket event
6.5 create websocket
Ws://echo.websocket.org/ is the address used for testing var socket = new WebSocket ('ws://echo.websocket.org/')
You can print the data by calling e.data.
Let's take a look at the close method.
6.6 websocket attribute
Benefits of 6.7 websocket
Both the client and the server can actively transmit data to each other.
Create TCP requests and destroy requests without frequency, reduce the consumption of network bandwidth resources, and save server resources at the same time
You can only request once, and the return will be updated automatically.
Thank you for reading this article carefully. I hope the article "what api in html5" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.