Object-oriented programming, or the mainstream, I also like to refine components, cutting objects. This way it looks clear, each object has a single responsibility, and there is no confusion.
The front end often deals with the browser. When dealing with some browser-related logic, it will call the browser API and sort out the API objects that will be used daily.
URL
Construct, parse, normalize, and encode urls.
Creating a URL object
Structural parameter description
url
If it is an absolute URL address, the second argument is ignored. If it is a relative path, base is used as the base URL.base
Base URL: does not take effect if the first parameter URL is an absolute URL.
// Specify the absolute ULR address
const url = new URL('http://www.baidu.com')
/ / or
const url = new URL(' '.'http://www.baidu.com')
// If a path exists
const url = new URL('http://www.baidu.com/hello')
/ / or
const url = new URL('/hello'.'http://www.baidu.com')
Copy the code
What are the attributes of the constructed URL instance object? You can obtain all the data information of the URL address from the graph:
Origin \searchParams is read-only, and other attributes can be set by variable assignment.
Modify related attributes:
// Modify the protocol
url.protocol = "ftp:" // href: 'ftp://www.baidu.com/hello',
// Modify the path
url.pathname = '/admin' // href: 'ftp://www.baidu.com/admin',
/ / append a hash
url.hash = 'app' // href: 'ftp://www.baidu.com/admin#app',
Copy the code
Instance methods
toString()
Returns the entire URLtoJSON()
, returns the entire URL, the same asurl.href
I thought there was anything different, but I found it was a cashback URL address.
There are also static methods that create a unique resource address link:
createObjectURL()
File, Blog, or MediaSource
Object that returns a unique blog link.revokeObjectURL()
Destroy the previous URL instance object of createObjectURL.
// File object, or bloB data
const dataUrl = URL.createObjectURL('blob:**')
// The created instance is destroyed. The access is invalid
URL.revokeObjectURL(dataUrl)
Copy the code
URLSearchParams object
So this should be the query string that we’re going to use a lot, to handle urls.
In the instance URL, there are search and searchParams(read only)
// Append a query condition to the url instance
url.search = 'id=45'
// Reread will contain? Pay attention to
console.log(url.search) / /? id=45
// Get the query parameter object of the instance URL
const searchParams = url.searchParams
Copy the code
Create an instance
- Optional arguments passed in are parsed, for example
? id=45
\id=45
I’m going to ignore the beginning?
const searchParams = new URLSearchParams()
/ /? id=45
const searchParams = new URLSearchParams("? id=45") // { 'id' => '45' }
// id=45&name=admin
const searchParams = new URLSearchParams("id=45&name=321") // { 'id' => '45', 'name' => '321' }
// [['id',45],['name','admin']]
const searchParams = new URLSearchParams([['id'.45], ['name'."admin"]])
// {'id':45,'name':'admin'}
const searchParams = new URLSearchParams({'id':45.'name':'admin'})
Copy the code
The advantage of instantiation is that it is easy to manage data, such as adding, deleting, and searching.
Instance methods
append(name,value)
– Add a datadelete(name)
– Deletes the data of the specified parameterentries()
– Iterates over key/value pairs of objects.get(name)
– Gets the first value of the specified parameter name.getAll(name)
– Returns all values of the specified parameter name, arrayhas(name)
– Checks whether a parameter exists.keys()
– Iterated object of keys for all parameters.set(name,value)
– Sets the value of a parameter.sort()
– Sort key names.toString()
– Returns the query string.values()
– An iterator containing all values.
const searchParams = new URLSearchParams()
// Append a parameter
searchParams.append("id"."sv2341") // { 'id' => 'sv2341' }
// Check whether a parameter is included
searchParams.has("name") // false
// Gets the value of the specified argument
searchParams.get("id") // sv2341
// Get the values of all parameters
[...searchParams.values()] // ['sv2341']
//
searchParams.toString(); / /.
Copy the code
Handle URL address parameters
You don’t need to separate strings to process query parameters yourself, and it’s much easier to process query parameters elegantly through the searchParams object.
// Get the query string object for the instance URL
const searchParams = url.searchParams
// Append a name query parameter
searchParams.append('name'.'admin') // href: 'ftp://www.baidu.com/admin?id=45&name=admin#app',
Copy the code
If it is a new URLSearchParams instantiated, it is copied to the URL object property Search
const url = new URL('http://www.baidu.com/hello')
// The newly instantiated object
const searchParams = new URLSearchParams()
searchParams.append("id"."sv2341")
searchParams.append("name"."test")
// Set query parameters
url.search = searchParams // href: 'http://www.baidu.com/hello?id=sv2341&name=test',
Copy the code
Unable to handle hash and pathName positional order
The tricky part is the hash and pathName placement, where the hash is always set after pathName \ search
const url = new URL('http://www.baidu.com')
/ / assignment hash
url.hash = '/'
// Assign path
url.pathname = '/app'
// Assign a query condition
url.search = 'id=45'
Copy the code
The result is displayed as http://www.baidu.com/app?id=45#/. I want the result to be http://www.baidu.com/#/app?id=45
Otherwise, when you open a new TAB, it will navigate to the original main route 😥
So we have to reconcatenate the URL:
const url = new URL('http://www.baidu.com/#/app')
const searchParams = new URLSearchParams()
searchParams.append("id"."sv2341")
searchParams.append("name"."test")
// Open a new TAB page
window.open(url.toString()+"?"+searchParams.toString()) // http://www.baidu.com/#/app?id=sv2341&name=test
Copy the code
File
Handle information related to documents. Access the data in the file. UTF8 encoding
Structure instance
Parameter definition:
bits
Defines the file contents, includingArrayBuffer\ArrayBufferView\Blob\DOMString[]
Such as the typename
File name, can append path.options
Optional configuration itemtype
– File MIME type, default ‘ ‘lastModified
The time when the file was modified
const file = new File(bits,name,options)
Copy the code
All accessible attributes are read-only:
lastModified
– Time when the file was last modifiedname
– File namesize
– File sizetype
– File type
Instance methods
There is no method defined itself, inherited from the Blob interface, optional parameter definition:
slice(start,end,contentType)
– Returns a new Blob object, the original piece of data.
// Customize the text content
const file = new File(['hello world'.'luck for you'].'test.txt')
Copy the code
FileReader
In order to read the contents of the file, we need the FileReader object to read the data.
Structure instance
const fileReader = new FileReader();
Copy the code
Accessible properties:
error
– An error occurred while reading the filereadyState
– Value status, 0- No data is loaded; 1- Data is being loaded; 2- Read completed.result
– Read the contents of the file.
Instance methods
An instance can be used to read a file, which is an asynchronous process. Asynchrony then has asynchronous flows that correspond to different events.
Let’s take a look at the method defined by the instance:
abort()
Abort read operationreadAsArrayBuffer()
Read content Saves data in an ArrayBuffer format.readAsDataURL()
Read the content and return the format asdata:
Base64 datareadAsText()
Read the content and return the content as a string.
Can continue the previous file data read;
// Define file objects
const file = new File(['hello world'.'luck for you'].'test.txt')
// Define the instance object that the file reads
const fileReader = new FileReader()
// Get the contents of the file via the onload event callback
fileReader.onload = function(event){
console.log(event.target.result) // hello worldluck for you
}
// Read the file as a string
fileReader.readAsText(file)
Copy the code
Here are all the events:
onabort
Triggered when an interrupt reads.onerror
An error occurred during the read operation.onload
Triggered when the read is complete.onloadstart
Triggered when the read startsonloadend
Read end trigger, success or failureonprogress
Triggered when a Blob object is read
Definition file download
Usually the front end handles simple file downloads, such as text, images, etc. The a tag is used for download processing
// Complete the simple customization.txt file download
const file = new File(['hello world'].'test.txt')
// Define the read file object
const fileReader = new FileReader()
// Read the file
fileReader.onload = function(event){
// Define the a tag, append it to the body, and click download
let a = document.createElement('a')
a.download = 'hello.txt'
a.href = event.target.result
a.textContent = 'download'
document.body.append(a)
}
// a tag downloads the accepted format blob: or data:
// Define to read base64 data
fileReader.readAsDataURL(file)
Copy the code
Can read remote URL address file information, download in the front end.
Usually a custom implementation of the download does not need to be clicked to trigger the download event
// Use the click method to simulate the click event and trigger the download
a.click()
// Define a tag is not visible
a.style.display = 'none'
Copy the code
throughURL.createObjectURL
Definition file download
You can read the contents of the file using FileReader, or you can create blobs using URL static methods: URL objects in the form of urls that point to the source content.
// Create a file content ULR
const dataUrl = URL.createObjectURL(file)
// Build the download
let a = document.createElement('a')
a.download = 'hello.txt'
a.href = dataUrl
a.textContent = 'download'
a.style.display = 'none'
document.body.append(a)
a.click();
Copy the code
Prepare to write about the file upload, download; Mainly resumable breakpoint, fragment upload, etc. I don’t know when I’ll finish it.
Image
Commonly used display form – picture, indispensable. Most websites don’t handle images, just get the ULR address and display it. If it is a special processing of the picture of the project, it will be on the picture of all aspects of the processing requirements. Usually get the size of the image, the initial canvas, etc.
Structure instance
The instance is equal to the HTML element img, which takes arguments
width
The width of theheight
highly
const img = new Image()
/ / is equivalent to
img = document.createElement('img')
Copy the code
Accessible attributes:
alt
Describing the contentcomplete
Indicates that the load is normal and no error occurs.crossOrigin
Cross domain setcurrentSrc
The URL that represents the image being loaded.decoding
Image decoding Settings after loadingheight
Height of CSS renderingwidth
Width of CSS renderingisMap
Is part of an image mappingnaturalHeight
Image inherent height; Different from the actual display size may be affected by CSS.naturalWidth
Image inherent width; Different from the actual display size may be affected by CSS.referrerPolicy
How to tell users how to obtain image resourcessrc
Image complete URLuseMap
Define the referencemap
The element#
At the beginningsrcset
List of candidate images, comma separated;w
Represents the image width,x
Representation of image densitysizes
Define the size of the image’s specific reality;
// Define an instance
const img = new Image(150.160)
img.src = './test.png'
// If the width and height are defined, the property img.width img.height can be obtained directly
img.onload = function(){
// To get the actual image size, you must wait for the image to load
// img.naturalWidth,img.naturalHeight
}
// Can be added to a page like a normal IMG tag
document.body.appendChild(img)
Copy the code
Instance methods
There are few major methods that provide calls,
decode()
It is used to decode the frame that loads the image, safely loading it into the DOM. Returns apromise
Inherit from the HTMLELement interface and have regular DOM events
onload
loadedonerror
Trigger the call when loading error occurs.
// The onload load is completed to obtain the actual image size information
img.onload = function(){
// To get the actual image size, you must wait for the image to load
// img.naturalWidth,img.naturalHeight
}
Copy the code
Img. widht/img.hegiht is the true size of the image.
Responsive image size
Nowadays, there are more and more electronic devices, and the screen size and separation are different. If you want to achieve perfect display effect, you must create pictures suitable for each size screen separation to display.
Defines image resources using srcset \ sizes of the image
<img srcset="1.png 500w, 2.png 800w, 3.png 1200w"
sizes="(max-width:520px) 500px, (max-width:820px) 800px, 1200px"
alt="Image"
/>
Copy the code
Check device widths and sizes list media queries that meet the criteria; Get the size of the defined display image and load it from srCset to the image that best fits the size size for display.
Different resolutions can be defined by srcset X;
MutationObserver
Provides the ability to monitor changes made to the DOM tree,
This is written in the source code when the vue instruction rolling load, after the business function will also use it to do some load optimization.
Structure instance
- The argument is a callback, that is, not to be called when dom changes to the specified node or child node.
- The first argument to the callback is a mutable array of MutationRecord objects.
- Instance object Observer
// Instantiate the observer object
const observer = new MutationObserver(handlerChange)
// Configure the DOM to listen to, and which properties to listen for change configurations
const options = {
childList:true.// Observe the changes of child nodes, add or remove
attributes:true.// Observe property changes
subtree:true.// Observe the descendant node
}
/ / to monitor
observe.observe(document.querySelector("#app"),options)
// Callback event
const handlerChange = function(mutationList,observer){
// Trigger variable nodes, attributes
}
Copy the code
Instance methods
-
Observe (DOM,options) – Configure to call the callback function when the dom given option to listen changes
const options = { attributeFiter: [].// set to listen on specified properties, such as width, height, etc. If not set, all properties are listened on. attributeOldValue:true.// When observing node properties change, record the old value attributes:true.// Observe the change of node properties characterData:true.// Listen for text changes in the text node characterDataOldValue:true.// Listen on the text node and record the old value of the text node childList:true.// Observe the addition and deletion of descendant nodes subtree:true.// Observe all changes to descendant nodes, properties, etc } Copy the code
Multiple calls to the listener method will remove the listener of the existing observation target. If the DOM is not specified, the existing observation target is retained and a new observer is added.
-
Disconnect () – Stops listening to the DOM, the callback is not called again
-
TakeRecords () – Removes all pending change notifications.
Initial data is loaded when scrolling
Before, we saw the instruction v-infinite-scroll of Element loading. During the initial data loading, API is used to monitor the changes of child nodes, so as to load the data content until the scroll bar appears. Our scroll load must have a scroll bar to start the scroll event.
(of course, we can judge the data by means of recursive return to the area offsetHeight/clientHeight comparing whether the scroll bar, then additional data)
But the automatic trigger processing logic is better 🙂
let id = 0
// The method to load data
function loadChild(){
id++;
let p = document.createElement('p')
p.textContent = ` data id${id}`
//
dom.appendChild(p)
}
// Instantiate the observer object
const observer = new MutationObserver(function(){
// Add child nodes when triggered
loadChild()
// Check if there is a scroll bar,
// There is no need to listen to DOM when there is a scrollbar
if(dom.scrollHeight > dom.clientHeight){
// There is a scroll bar
if(observer){
observer.disconnect();
observer = null; }}})// Configure the DOM to listen to, and which properties to listen for change configurations
const options = {
childList: true.// Observe the changes of child nodes, add or remove
attributes: false.// Observe property changes
subtree: false.// Observe the descendant node
}
/ / to monitor
let dom = document.querySelector(".list-box");
observer.observe(dom, options)
// Initial call once
loadChild();
// Then normal Scroll event listener
dom.addEventListener('scroll'.function(){
// Scroll distance + viewable height <= Content area height -20 append data
let scrollBottom = dom.scrollTop + dom.clientHeight
if(dom.scrollHeight - scrollBottom <= 20){ loadChild(); }})Copy the code
To trigger the initial change of the target node, the data loading function loadChild() is called manually. When the first data is added, the DOM listening callback is executed. Stop detection until the scrollbar appears (the viewable height is not equal to the content area height).
The normal scroll event is monitored. When the bottom scroll distance is less than 20(threshold), the data loading function is triggered.
When the data is loaded, you can add the unscrolling event to the loadChild function to stop the scrolling loading time trigger.
MutationRecord
Callback the first parameter after listening for DOM changes.
type
– Type of change, attributes – Attributes; Node text change – characterData; Child node changes – childListtarget
– The target node of the changeaddedNodes
– NodeList of the added noderemovedNodes
– Node NodeList to be removedoladValue
– Old value record before change, need to configure the attribute will have;- .
FormData
Provides the ability to process form data. Form processing is ubiquitous in daily development. The current front-end framework helps me deal with this problem well, and necessary learning is still necessary.
Structure instance
- Parameters for
form
Label DOM object, optional.
//
const form = new FormData()
Copy the code
When we pass in the form parameter, we must have the name attribute for each form element. The form values are automatically serialized
// Specify the form element to synchronize the form attributes and values in the form.
const form = new FormData(document.querySelector('#form'))
Copy the code
Instance methods
append()
Key /value Adds a key/value pair. If a key exists, a value is addeddelete()
Delete a specified keyentries()
The iterator of all key-value pairsget()
Gets the first value of the specified keygetAll()
Returns an array of all values for the specified keyhas()
Whether a key is includedkeys()
Iterators for all property keysset()
Sets the property value to override the original valuevaluse()
Returns an iterable object containing all attributes
<form id="form">
<div class="form-item">
<label>The name</label>
<input type="text" name="name" value="admin" placeholder="Enter name" />
</div>
<div class="form-item">
<label>age</label>
<input type="number" min="0" name="age" value="23" max="200" step="1" />
</div>
<div class="form-item">
<label>gender</label>
<input type="radio" name="gender" value="1" checked>male<input type="radio" name="gender" value="2">female</div>
</form>
Copy the code
Defines the form form that, after creating the FormData instance, operates on the form elements and can add new attributes.
// All attributes are serialized by the name attribute of the form element
form.keys() // [...keys] - result:["name", "age", "gender"]
// Find a value
form.has('id') // false
// Add a value, repeating the name attribute
form.append('name'.'test')
form.get('name') // return the first matching value, which is admin
form.getAll('name') // Return all worth arrays, ['admin','test']
Copy the code
XMLHttpRequest sends data
Create an Ajax instance and send the request.
// Send data directly
const xhr = new XMLHttpRequest()
xhr.open('post'.'/addUserInfo')
xhr.send(form)
Copy the code
Create and upload files using File.
// Create a file object
const file = new File(['hello world'].'test.txt')
// Define the instance object that the file reads
const fileReader = new FileReader()
// Define the request instance
const xhr = new XMLHttpRequest()
// Get the contents of the file via the onload event callback
fileReader.onload = function(event){
// Read file BLOB data
form.append('file',event.target.result)
xhr.open('post'.'/addUserInfo')
xhr.send(form)
}
// Read the file as a string
fileReader.readAsDataURL(file)
Copy the code
As aURLSearchParams
Structural parameter analysis
You can pass URLSearchParams directly for parsing and then append it to the URL.
//
const params = new URLSearchParams(form)
// Get the method to use the instance
params.toString() // name=admin&age=23&gender=1&name=test
Copy the code