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.

  1. videoThe element is used to play video over the network
  2. audioThe 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

audioElements andvideoThe 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.

networkStateattribute

The networkState property is used to read the current network status.

  • network_emptyIs the initial state of the element
  • network_idleWhat encoding has been processed for the browser to play media, but the network connection is not established
  • network_loadingLoading for media data
  • network_no_sourceLoad is not performed for an unsupported encoding format

currentSrcattribute

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:

  1. TimeRanges.start(0)When does the current cache area start to be cached
  2. TimeRanges.end(0)When does the current cache area end the cache

readyStateattribute

The readyState property returns the readyState of the current playback position of the media.

  1. have_nothingIndicates that no media information is obtained and no data can be played at the current playing position.
  2. have_metadataIndicates that sufficient media data has been obtained, but no valid media data is available at the current play location.
  3. have_current_dataRepresents 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.
  4. have_future_dataRepresents the data that is currently playing and the data that is playing forward. When the last frame is playing,readyStateProperty cannot behave_future_data.
  5. have_enough_dataIndicates that both the current and forward data are being played, ensuring sufficient data for subsequent playback.

seekingProperties andseekableattribute

The seeking property returns a Boolean value:

  1. trueIndicates that the browser is requesting data
  2. falseIndicates that the browser has stopped the request

The seekable property returns a TimeRanges object that represents the time range for the requested data.

  1. Start time: the time when the first frame of data is requested
  2. End time: The time when the last frame of data is requested

currentTimeProperties,startTimeProperties,durationattribute

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.

playedProperties,pausedProperties,endedattribute

The played property returns a TimeRanges object representing the time period in which the played portion of the media file was read.

  1. Start time Indicates the start time
  2. End time Indicates the end time that has been played

The paused property returns a Boolean value indicating whether playback is paused

  1. truePause play
  2. falseIs playing

defaultPlaybackRateProperties andplaybackRateattribute

DefaultPlaybackRate reads or modifies the defaultPlaybackRate of the media

PlaybackRate property reads or modifies the current playbackRate of the media.

volumeProperties andmutedattribute

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

  1. trueMute state
  2. falseIs in the unmuted state

methods

There are four methods:

canPlayTypemethods

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 StorageWith 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 understandsessionStorageandlocalStorageAnd the difference between the two
  • openDatabaseMethod to create and open a database
  • transactionMethod 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:

  1. localStorageThe correspondingwindow.localStorage
  2. sessionStorageThe correspondingwindow.sessionStorage

localStorageThe advantage of

  1. localStorageExpand thecookie4KRestrictions.

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.

localStorageThe 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.

  • localStorageThis is essentially a string read, and if you store a lot of content it will consume memory and cause the page to get stuck.
  • localStorageCan’t be caught by crawlers.

localStorageuse

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 LocalStorageThe 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.

cookiesProblems with storing persistent data.

Web StorageDivided into two kinds:

  1. sessionStorageAnd stores the data insessionObject, which is the period of time when the user is browsing a website, from when the user enters to when the browser closes,sessionObject can be used to store any data that is required during that time.
  2. 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 Storageinterface

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.

  • saveStoragefunction
  • loadStoragefunction
  • clearStoragefunction

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.

useSQLLiteThe database

  1. Create objects that access the database
  2. 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

withexecuteSqlTo 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 offlinewebThe 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:

  1. Offline resource caching
  2. Online status detection
  3. 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 StorageTwo categories

DOM Storage is divided into sessionStorage and localStorage.

The difference between local caching and browser web caching

  1. Local caching serves the entire Web application, whereas browser web caching serves individual web pages.
  2. Any web page has a web page cache, and the local cache is only those pages that the user specifies to cache.
  3. Web caching is not secure, unreliable, and it is not known exactly which pages and resources it caches.
  4. The local cache is reliable and gives you control over what is cached and not cached.

The interviewer asks: What ismanifestfile

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 isapplicationCacheobject

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:

  1. The browser requests access to the address
  2. Server returnindex.htmlWeb page
  3. Browser parsingindex.htmlWeb page, request all resource files on the web page
  4. The server returns all resource files
  5. Browser processingmanifestFile, requestmnifestAll files that require local caching in.
  6. The server returns all files that require a local cache.
  7. The browser updates the local cache and notifies the local cache that it is updated.

swapCachemethods

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”.

  1. The agreement is the same
  2. Domain name is the same
  3. 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 Socketscommunication

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

  1. Service WorkerandcacheStorageCaching and offline development
  2. Caching and offline development
  3. In an easy-to-understand wayService Worker
  4. Learn about global objects in JSwindow.selfAnd global scopeself
  5. To understandCacheandCacheStorage
  6. With the help ofService WorkerandcacheStorageSet pieces for offline development
  7. andPWARelationship of technology
  8. offlinewebApplication, when the client is local withwebThis can be used locally on the client even when the application server is not connectedwebThe 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.