preface
Hi, everyone! I want to go out and play Nezha.
Recently, there are more and more good news about the epidemic. Life has started to return to normal and people are gradually getting back to work. No more words, and study.
Let’s take a look at the likes and comments from diggers.
multimedia
Multimedia, what do you have in mind? I think of the video element and the audio element.
Learn about elements, including properties, methods, and events. Before THE emergence of HTML5, display video, audio, animation, etc., are the use of third-party independent development, the most used tool is Flash.
There is no need to install plug-ins for audio and video interfaces now provided through HTML5 technology.
Media is a general term for audio and video.
video
The element is used to play video over the networkaudio
The element is used to play audio over the network
Use audio:
<audio src="http://test.mp3">
</audio>
Copy the code
Use the video element:
<video width="640" height="360" src="">
</video>
Copy the code
Use the source element: This element can specify multiple playback formats and encodings for the same media data to ensure that the browser can select one of its supported playback formats for playback.
<video>
<source src="test.ogv" type='video/ogg; codecs="theora, vorbis"'>
<source src="text.mov" type="video/quicktime">
</video>
Copy the code
Determine whether you support the format from top to bottom until you find it.
parameter | describe |
---|---|
src | Url of the playing media |
type | The media type |
audio
Elements andvideo
The element
Common attributes:
<video src="text.mov" autoplay></video>
parameter | describe |
---|---|
src | Specifies the URL address of the media data |
autoplay | Specifies whether the media plays automatically after the page loads |
preload | Specifies whether video or audio data is preloaded |
loop | Specifies whether to loop video or audio |
controls | Specifies whether to add the browser’s own playback control bar for video or audio |
The value of the preload property, none, indicates that preloading is not performed. Metadata preloads only media metadata. Auto Preloads all videos or audio files.
<video src="" preload="auto"></video>
Poster is a unique attribute of the video element. When the video is unavailable, this element can be used to replace it with a picture to avoid blank space in the video area.
<video src="" poster="image.jpg"></video>
<video src="" autoplay loop></video>
<video src="" controls></video>
Width and height are the width and height of the video and are attributes unique to the video element.
<video src="" width="500" height="500"></video>
The error properties
Normally, the error attribute of the video or audio element is null.
When an error occurs, a MediaError object is returned, and the code of this object returns the value of the error status for.
Media_err_aborted, the download of media data is aborted due to user’s operation.
Media_err_network, confirm that the media resource is available, but a network error occurred during the download, and the download of media data was stopped.
Media_err_decode, confirming that the media resource is available, but an error occurred while decoding.
Media_err_src_not_supported The media format is not supported.
networkState
attribute
The networkState property is used to read the current network status.
network_empty
Is the initial state of the elementnetwork_idle
What encoding has been processed for the browser to play media, but the network connection is not establishednetwork_loading
Loading for media datanetwork_no_source
Load is not performed for an unsupported encoding format
currentSrc
attribute
CurrentSrc The URL used to read data from playing media
Buffered properties
Using the buffered property returns an object that implements the TimeRanges interface to verify that media data has been cached.
The TimeRanges object represents a time range. In general, the TimeRanges object represents a time range as a single range starting with 0.
If the browser issues Range Requests, the TimeRanges object represents multiple TimeRanges.
In this object, there is a length attribute that indicates how many time ranges there are.
In general, the value is 1 when a time range exists. If no time range exists, the value is 0.
In general, index is 0:
TimeRanges.start(0)
When does the current cache area start to be cachedTimeRanges.end(0)
When does the current cache area end the cache
readyState
attribute
The readyState property returns the readyState of the current playback position of the media.
have_nothing
Indicates that no media information is obtained and no data can be played at the current playing position.have_metadata
Indicates that sufficient media data has been obtained, but no valid media data is available at the current play location.have_current_data
Represents data that has been played, but no data to move the player forward. A video has data for the current frame, but no data for the next frame, or the last frame.have_future_data
Represents the data that is currently playing and the data that is playing forward. When the last frame is playing,readyState
Property cannot behave_future_data
.have_enough_data
Indicates that both the current and forward data are being played, ensuring sufficient data for subsequent playback.
seeking
Properties andseekable
attribute
The seeking property returns a Boolean value:
true
Indicates that the browser is requesting datafalse
Indicates that the browser has stopped the request
The seekable property returns a TimeRanges object that represents the time range for the requested data.
- Start time: the time when the first frame of data is requested
- End time: The time when the last frame of data is requested
currentTime
Properties,startTime
Properties,duration
attribute
The currentTime property is used to modify the current playing position, as well as the current playing position of the reading media.
StartTime property to read the startTime of media playback, usually 0.
Duration reads the total playing time of a media file.
played
Properties,paused
Properties,ended
attribute
The played property returns a TimeRanges object representing the time period in which the played portion of the media file was read.
- Start time Indicates the start time
- End time Indicates the end time that has been played
The paused property returns a Boolean value indicating whether playback is paused
true
Pause playfalse
Is playing
defaultPlaybackRate
Properties andplaybackRate
attribute
DefaultPlaybackRate reads or modifies the defaultPlaybackRate of the media
PlaybackRate property reads or modifies the current playbackRate of the media.
volume
Properties andmuted
attribute
Volume property: Reads or modifies the playback volume of the media. The value ranges from 0 to 1
A fraternal attribute reads or modifies the muted state of the media and has a Boolean value
true
Mute statefalse
Is in the unmuted state
methods
There are four methods:
canPlayType
methods
The canPlayType method tests whether the browser supports the specified media type
var support = videoElement.canPlayType(type)
The event
Perform a series of events on media data.
The first:
videoElement.addEventListener(type,listener,useCapture)
video.addEventListener("error", function()
{
...
},false);
Copy the code
The second:
< video id = "video1" SRC = "" onplay =" the begin ();" ></video> function begin() { ... }Copy the code
Event method
The event | describe |
---|---|
loadstart | The browser starts looking for media data |
progress | The browser is fetching media data |
suspend | The browser pauses to retrieve the media data, but the download process does not end |
abort | Abort media data retrieval, not caused by an error |
error | Error getting media data |
emptied | The network becomes uninitialized: 1. An error occurs during the loading of media. 2. The load method is called when the browser selects the supported playback format |
stalled | The browser failed to obtain media data |
play | play |
pause | Play to suspend |
loadedmetadata | Length of time and number of bytes for the browser to complete retrieving media |
loadeddata | The browser has finished loading the current playing media data |
waiting | The playback is paused without getting the next frame, but soon resumes to get the next frame |
playing | There is |
canplay | Yes. The rate at which the media is played cannot be directly finished. Buffering is required during the playback |
canplaythrough | It can play, and the playback rate can also play, so you don’t have to buffer |
seeking | When true, data is being requested |
seeked | When false, it stops requesting data |
timeupdate | Indicates that the current playing position has been changed |
ended | Stop playing when it ends |
ratechange | The defaultplaybackRate property or playbackRate property is changed |
durationchange | The playback time has been changed |
volumechange | The volume, volume attributes were changed, or the muted state decreased |
The local store
web Storage
With local databases
HTML5 in two important content: Web Storage and local database.
Web Storage Storage mechanism is an improvement of HTML4 cookies Storage mechanism, HTML5 to try improved Web Storage mechanism.
Local database is a new feature in HMTL5, which can be saved in the client to create a local database. — Greatly reduces the burden on the server side and speeds up the speed of accessing data.
- To understand
sessionStorage
andlocalStorage
And the difference between the two openDatabase
Method to create and open a databasetransaction
Method to process a transaction
sessionStorage
The sessionStorage property allows you to access a sessionStorage object. It is similar to localStorage except that data stored in localStorage does not have an expiration date, while data stored in sessionStorage is cleared when the page session ends.
The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
The top-level browsing session context is copied as the context for the new session when a new TAB or window opens a page, unlike session cookies.
grammar
// Save data to sessionStorage sessionstorage. setItem('key', 'value'); Let data = sessionstorage.getitem ('key'); let data = sessionStorage.getitem ('key'); / / delete saved data from sessionStorage sessionStorage. RemoveItem (" key "); Sessionstorage.clear (); // Delete all saved data from sessionStorage.clear();Copy the code
The Window sessionStorage properties
// Store sessionstorage. setItem("lastname", "Jeskson"); // Retrieve document.getelementById ("result").innerhtml = sessionStorage.getitem (" lastName ");Copy the code
Definition and Use
The localStorage and sessionStorage properties allow key/value pair data to be stored in the browser
SessionStorage is used to temporarily store data of the same window, which will be deleted after closing the window or TAB.
If you want to preserve data after the browser window closes, use the localStorage property
localStorage
The read-only localStorage property allows you to access a Document source object Storage; The stored data is saved in the browser session.
Data stored in localStorage can be retained for a long time. When the page is closed, the data stored in sessionStorage is erased.
SetItem ("lastname", "Jeskson"); // Retrieve document.getelementById ("result").innerhtml = localstorage.getitem (" lastName ");Copy the code
There are two apis in the browser:
localStorage
sessionStorage
Exists in the window object:
localStorage
The correspondingwindow.localStorage
sessionStorage
The correspondingwindow.sessionStorage
localStorage
The advantage of
localStorage
Expand thecookie
的4K
Restrictions.
LocalStorage stores the first request directly to the local database, which is equivalent to a 5M database size. This saves bandwidth compared to cookies, which are only supported in older browsers.
localStorage
The limitations of
Browsers have different sizes, and Internet Explorer versions later than Internet Explorer 8 support localStorage.
Most browsers limit the value type of localStorage to string. This common JSON object type requires some conversion.
LocalStorage is not readable under the browser’s privacy mode.
localStorage
This is essentially a string read, and if you store a lot of content it will consume memory and cause the page to get stuck.localStorage
Can’t be caught by crawlers.
localStorage
use
To use localStorage, I need to check whether the browser supports localStorage:
if(! LocalStorage){alert(" Browser does not support localStorage "); return false; }else{// main logical business}Copy the code
In particular
The use of localStorage also follows the same origin policy. Different websites cannot share the same localStorage.
LocalStorage supports only string storage.
JSON will be stored in localStorage, which will automatically convert localStorage to a string.
Convert JSON to a JSON string using the json.stringify () method. To convert the JSON string to a JSON object after reading it, use the json.parse () method.
HTML5 LocalStorage
The local store
What is theWeb Storage
With network storage, Web applications can store data locally in the user’s browser.
Prior to HTML5, application data had to be stored in cookies that were included in every server request. Network storage is more secure, and large amounts of data can be stored locally without affecting site performance.
Web storage is per-origin (per domain and protocol). All pages, from one origin, can store and access the same data.
Web Storage stores data on the Web.
Web Storage A Web Storage function that stores data locally on clients.
cookies
Problems with storing persistent data.
Web Storage
Divided into two kinds:
sessionStorage
And stores the data insession
Object, which is the period of time when the user is browsing a website, from when the user enters to when the browser closes,session
Object can be used to store any data that is required during that time.localStorage
, the data is stored in the local hardware device of the client. After the browser is closed, the data is still there. The next time you open the browser to visit the website, you can continue to use it.
Method of use
sessionStorage
- Save data:
sessionStorage.setItem(key,value)
- Read data:
Variable = sessionStorage. The getItem (key)
localStorage
- Save data:
localStorage.setItem(key,value)
- Read data:
Variable = localStorage. The getItem (key)
Web Storage has the following two mechanisms
SessionStorage and localStorage
Web Storage
interface
Storage
Allows you to set, retrieve, and delete data and store types in a specific domain
Window
The Web Storage API inherits from the Window object and provides two new properties
Window.sessionStorage
Window.localStorage
They provide access to the session and local Storage objects of the current domain, respectively.
StorageEvent
When a store changes, stored events are published from the document’s Window object.
saveStorage
functionloadStorage
functionclearStorage
function
Convert objects to jSON-formatted text data using the Stringify method of JSON objects.
var str=JSON.stringify(data);
Convert the data obtained from localStorage into a JSON object.
var data = JSON.parse(str);
Simple database script code:
function saveStorage()
{
var data=new Object;
data.name=document.getElementById('name').value;
var str = JSON.stringify(data);
localStorage.setItem(data.name, str);
}
function findStorage(id)
{
var find = document.getElementById('find').value;
var str = localStorage.getItem(find);
var data = JSON.parse(str);
var result = data.name;
var target = document.getElementById(id);
target.innerHTML = result;
}
Copy the code
cookie
(Data stored on the user’s local terminal)
A Cookie is a plain text file stored on the client. For example, TXT files.
The client is our own local computer. When we access a web page through our browser, the server generates a certificate that is returned to my browser and written to our local computer.
This certificate is a cookie. In general, cookies are plain text files written by the server to the client.
Cookie files are supported by the browser, where you can set to prevent cookies. The server cannot write cookies to the client.
In general, cookies cannot be blocked, so they cannot be accessed.
When the server receives an HTTP request, it can add a set-cookie option to the response header.
The server sends Cookie information to the user agent using the set-cookie response header.
The file SQL database that does not need to be stored on the service is called SQLLite.
useSQLLite
The database
- Create objects that access the database
- Using transactions
Var db = openDatabase('mydb', '1.0', 'Test db', 2 * 1024 * 1024);
Returns the created database access object. If the database does not exist, create it.
parameter | describe |
---|---|
The first parameter | The database name |
Second parameter | The version number |
The third parameter | Database Description |
The fourth parameter | Database size |
The Transaction method is called to perform transaction processing.
The transaction method:
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS(id unique,Log)');
})
Copy the code
withexecuteSql
To execute the query statement
The executeSql method:
transaction.executeSql(sqlquery,[],dataHandler,errorHandler);
parameter | describe |
---|---|
The first parameter | SQL statement to execute |
Second parameter | Requires an array of parameters used in the SQL statement |
The third parameter | The callback function that is called when the SQL statement is successfully executed |
The fourth parameter | The callback function that is called when an error occurs in executing an SQL statement |
Code:
ExecuteSql ('UPDATE people set age=? where name=? ; ', [age,name]); Function dataHandler(transaction,results){} function errorHandler(transaction, errmsg){}Copy the code
Offline application
HTML5 provides an API for the use of local caching, which enables the development of offline Web applications.
Interviewer asks: What is offlineweb
The application
HTML5 offline functionality, support for offline application development is a new feature in HTML5.
There are three things you need to know about offline Web applications:
- Offline resource caching
- Online status detection
- Local data store
What is offline resource caching
HTML5 provides an application caching mechanism that allows Web-based applications to run offline.
Is a way to name resource files that your application needs to work offline. This allows these files to be cached locally while the browser is online, and then loaded automatically when the user accesses the application while offline, allowing the user to browse.
In HTML5, cache manifest represents the cached resources through the use of cache manifest and supports both automatic and manual caching.
What is online testing
Developers need to know if the browser is online, manipulate it, and in HTML5, provide a way to check if the web is currently online.
What is local data caching
When offline, data is stored locally. To meet the needs, HTML5 provides DOM Storage and Web SQL Database Storage mechanisms.
HTML5’s DOM Storage mechanism provides a way for programmers to store information on a local computer and retrieve it when needed.
DOM Storage
Two categories
DOM Storage is divided into sessionStorage and localStorage.
The difference between local caching and browser web caching
- Local caching serves the entire Web application, whereas browser web caching serves individual web pages.
- Any web page has a web page cache, and the local cache is only those pages that the user specifies to cache.
- Web caching is not secure, unreliable, and it is not known exactly which pages and resources it caches.
- The local cache is reliable and gives you control over what is cached and not cached.
The interviewer asks: What ismanifest
file
The local cache of a Web application is managed through the manifest file for each page. The manifest file is a simple text file.
In order for the browser to read the text file properly, you need to specify the URL of the MANIFEST file in the MANIFEST attribute of the HTML tag on the Web application page.
The interviewer asks: What isapplicationCache
object
The applicationCache object represents the local cache and is used to notify the user that the local cache has been updated.
Code:
ApplicationCache. OnUpdateReady = function () {/ / local cache is updated, notify the user alert ()};Copy the code
Browser-server interaction
Process:
- The browser requests access to the address
- Server return
index.html
Web page - Browser parsing
index.html
Web page, request all resource files on the web page - The server returns all resource files
- Browser processing
manifest
File, requestmnifest
All files that require local caching in. - The server returns all files that require a local cache.
- The browser updates the local cache and notifies the local cache that it is updated.
swapCache
methods
The local cache is ready to be updated. This method is used to manually perform a local cache update.
Use the premise
The updateReady event in the applicationCache object is invoked, and the updateReady event is only updated in the manifest file on the server, after the requested resource file in the MANIFEST file is downloaded locally.
Code:
ApplicationCache. OnUpdateReady = function () {/ / local cache is updated, notify the user alert (); applicationCache.swapCache(); }Copy the code
Cross document message transfer
What is homology? “homology” means “three of the same”.
- The agreement is the same
- Domain name is the same
- The same port
The purpose of same-origin is to ensure the security of user information and prevent malicious websites from stealing data. Co-domain restriction refers to the same protocol, same domain name, and same port address for communication.
With the cross-document message transfer function, messages can be transmitted between different web pages, different ports and different domains.
Monitors message events for window objects.
Code:
window.addEventListener("message", function(){... },false);Copy the code
Use the postMessage method of the window object to send messages to other Windows.
otherWindow.postMessage(message, targetOrigin);
parameter | describe |
---|---|
The first parameter | The text of the message to be sent |
Second parameter | The URL of the object window that receives the message |
Web Sockets
communication
Web Sockets are a non-HTTP communication mechanism between client and server in Web applications provided by HTML5.
If you have HTTP, why do you need another protocol?
Because of a flaw in the HTTP protocol, communication can only be initiated by the client. (The client makes a request to the server, and the server returns the query results.)
The biggest feature of WebSocket protocol is that the server can automatically push messages to the client, and the client can also actively send messages to the server.
The WebSocket object is used as a constructor to create a new WebSocket instance.
The onopen property of the instance object, specifying the callback function if the connection is successful.
Code:
ws.onopen = function () { ws.send('Hello Server! '); }Copy the code
Use the addEventListener method
ws.addEventListener('open', function (event) { ws.send('Hello Server! '); });Copy the code
Code, a simple example of the client:
var ws = new WebSocket("wss://index.org"); ws.onopen = function(evt) { console.log("Connection open ..." ); // The send() method of the instance object is used to send data to the server. ws.send("Hello WebSockets!" ); }; Ws.onmessage = function(evt) {console.log("Received Message: "+ evt.data); ws.close(); }; Onclose = function(evt) {console.log("Connection closed."); };Copy the code
Code:
// When the connection is open, send some data to the server // When the connection is open, send some data to the server Connection.onopen = function () {// The send() method of the instance object is used to send data to the server. connection.send('Ping'); // Send the message 'Ping' to the server }; // Log errors // The onerror property of the instance object, which specifies the callback function when an error is reported. connection.onerror = function (error) { console.log('WebSocket Error ' + error); }; // The onMessage property of the instance object, which specifies the callback function after receiving data from the server. connection.onmessage = function (e) { console.log('Server: ' + e.data); };Copy the code
What is a WebSocket?
WebSocket is a network communication protocol.
Code:
var webSocket = new WebSocket("");
Copy the code
The URL string must begin with a WS or WSS (encrypted communication) literal.
Use the WebSocket object’s send method to send data to the server. Only text data can be sent.
Code:
webSocket.send("data");
Copy the code
Receive data from the server by getting the onMessage event handle:
Code:
webSocket.onmessage = function(event){
var data = event.data;
}
Copy the code
Listen for the socket opening event by getting the onOpen event handle:
Code:
Websocket. onopen = function(event){Copy the code
Listen for a socket closure event by getting an onclose event handle:
Code:
Websocket. onclose = function(event) {};Copy the code
Use the close method to close the socket and disconnect the communication connection.
webSocket.close()
A typical Websocket handshake request
Client request
Server Response
reporter
Service Worker
andcacheStorage
Caching and offline development- Caching and offline development
- In an easy-to-understand way
Service Worker
- Learn about global objects in JS
window.self
And global scopeself
- To understand
Cache
andCacheStorage
- With the help of
Service Worker
andcacheStorage
Set pieces for offline development - and
PWA
Relationship of technology - offline
web
Application, when the client is local withweb
This can be used locally on the client even when the application server is not connectedweb
The application performs related operations.
Refer to the address
developer.mozilla.org/zh-CN/
www.ruanyifeng.com/blog/2017/0…
The last
Welcome to add my wechat Jeskson(xiaoda0423), pull you into the technology group (nuggets – front university), long-term exchange and study.