Web front-end technology consists of HTML, CSS, and JavaScript, and is a large and complex technology system that is not less complex than any other backend language. When we learn it is often to start from a certain point, and then constantly contact and learn new knowledge points, it is difficult for beginners to understand the whole system of the context structure. In this paper, the knowledge system of Web front-end is simply combed, the corresponding knowledge points are donuts and not introduced in detail. The purpose is to help you review whether your knowledge structure is perfect, and if there are omissions or incorrect places, we hope to encourage mutual encouragement.
One, JAVASCRIPT article
0. Basic Grammar
The basic Javascript syntax includes: variable declarations, data types, functions, control statements, built-in objects, and so on.
In ES5, there are two ways in which variable declarations are var and function, Var is used to declare ordinary variables, to receive arbitrary types, and function to declare functions. In addition, ES6 adds four commands such as let, const, import, and class to declare common variables, static variables, modules, and classes, respectively.
There are six types of JS data, String, number, Boolean, Null, Undefined, and Object, respectively, and ES6 new Symbol type. Where Object is a reference type, and the other is the original type (Primitive type).
The primitive type, also known as the base type or simple type, because it occupies space fixed, is a simple data segment, in order to facilitate the variable query speed, stored in the stack (by value access). To facilitate the operation of such data, ECMAScript provides 3 basic wrapper types : Boolean, Number, and String. The basic wrapper type is a special type of reference, and whenever a basic type value is read, JS internally creates a corresponding wrapper object, which can be invoked to manipulate the data.
A reference type cannot be stored in the stack because its value is changed, so it is stored in the heap, the value stored in the variable is a pointer, to the memory of the storage object (accessed by the site), and for the value of the reference type, you can add properties and methods to it. You can also change and delete its properties and methods, but you cannot add properties and methods to the base type.
Javascript can use typeof to determine the original data type, but cannot judge the reference type, to know the specific type of reference type, you need to use the ToString method on the Object prototype to determine
There are three roles in JS function: normal function, constructor, object method. The same function, the invocation way, the function is different, the role is not the same. The direct invocation is the normal function, which is the constructor when the object is created by new, and is the method when called by the object.
JS commonly used built-in objects such as window, Date, Array, JSON, REGEXP, etc., window is a browser in the execution of the script when the global object, mainly describes the browser window related properties and state, this later, the Date and Array use the most scenes, JSON is primarily used for the serialization and deserialization of objects, and one effect is to implement deep copies of objects. REGEXP is the regular expression, which is a powerful tool for processing strings.
1. Function prototype chain
JS is an object-based language, but before ES6 is not support inheritance, in order to have the ability to inherit, Javascript on the function object on the establishment of the prototype object prototype, and the function object as the main line, from top to bottom, in the JS internal construction of a prototype chain. The prototype chain links individual objects together, and object is the ancestor of all objects, and the prototype chain created by any object eventually points to object and ends with object.
Simply put, a variable lookup mechanism is established, and when the property of an object is accessed, the object itself is found, and if it does not exist, it goes to the prototype where the object is located, until the object is found, and the property is not returned if it is undefined. Therefore, we can implement the inheritance mechanism through the prototype chain.
2. Function Scope
Function scopes are defined by variables in the body of the function in which they are declared and in any function within which the body of the function is nested. In layman's terms, in a function, some variables can be accessed and some cannot be accessed. The range of variables that can be accessed is the scope of the function.
In JavaScript, there is no block-level scope, only the function scope, that is, if, while, the For statement does not form a separate scope. However, there is a special case where the WITH statement and the Catch statement form a temporary scope, which is freed when the statement execution is finished.
3. This pointer
The this pointer exists in the function to identify the context in which the function is running. This is different from the type of the function: for normal functions, this always points to the Global object window; For constructors, this points to the newly created object, and for the method, this points to the object that called the method. In addition, the function object also provides methods such as call, apply, and bind to change the this point of the functions, where call and apply active execution functions, bind is generally used in the event callback, and the difference between call and apply is only the way the parameters are passed differently.
If you go deep to understand, no matter what function, this is changed, in essence, this all points to the object that triggered the function when it was run. The value of this cannot be changed while the function is running.
4. New operator
There are three ways to create a function, that is, explicit declaration, anonymous definition, and new function (). As mentioned earlier, the function in JS can be a function, it can be a method, it can also be a constructor.
When using new to create an object, the function is a constructor, JS points the prototype chain of the new object to the prototype object of the constructor, so a prototype chain is established between the new object and the function object, and the new object can access the methods and properties in the prototype prototype of the function object.
5. Closed Package
Closures are not an isolated concept and need to be understood from the perspective of the function scope.
Each function has its own scope, if another function is defined in a function, then there are two scopes, the two scopes will form a chain, commonly known as the scope chain. In essence, the scope chain is a top-down list, the top of the list is the scope of the inner function, the bottom of the list is the global scope. Intrinsic functions have access to variables on the whole scope chain. Normally, whenever a function is executed, the corresponding scope is removed from the list and then destroyed.
However, if function A returns the function B as the return value, the situation is different.
First, function A returns a reference to function B, which means that B may be called elsewhere. As mentioned above, function B is defined inside function A, so a and B form a scope chain, and function B may read the variables in a. To ensure that function B can execute correctly elsewhere, the scope chain where function B resides cannot be destroyed. Therefore, even after function A performs a return, the scope of a is not freed and needs to be kept in memory to ensure that function B reads the variables inside. Function B has the privilege of permanently accessing a scope, specifically, function B is the closure.
6. Single thread and event loop
Javascript is a single-threaded language. In the browser, when the JS code is loaded, the browser assigns it a main thread to perform the task, and the main thread creates a global execution environment (global scope) in the stack. Whenever a function enters the execution stream, a corresponding execution environment (function scope) is formed, and the execution environment is pushed into the stack. Each time a function is executed, the corresponding execution environment is ejected from the stack and then destroyed. This is the execution environment stack, the role of the execution environment stack is to ensure that all functions can be executed in the correct order.
But in the browser, there are some tasks that are time-consuming, such as AJAX requests, timers, events, and so on. To ensure that the main thread task is not affected, Javascript internally maintains a task queue, and when these time-consuming tasks end (Ajax request returns, timer timeouts, events are triggered), the corresponding callback function is inserted into the queue to wait. The execution time of these tasks is not deterministic, only after all synchronization tasks have been completed, the execution environment stack is emptied (the global execution environment at the bottom of the stack will persist until the process exits), then the callback function is read sequentially from the task queue and pressed into the execution environment stack. As a result, the main thread begins to perform a new synchronization task, and then pops out of the stack after execution, and the stack is emptied.
The main thread reads the task from the task queue continuously, and each time the stack is emptied, the main thread reads the new task from the task queue and executes it, and waits until there is a new task until a new task is available. This execution mechanism of JavaScript is called the task cycle. Because each task is triggered by an event, it is also called an event loop.
7. Asynchronous Communication Ajax Technology
Ajax is the asynchronous communication technology that the browser uses to interact with the server, and its core object is XMLHttpRequest, through which an AJAX request can be created. The AJAX request is a time-consuming asynchronous operation, and when the request is issued, AJAX provides two status bits to describe the state of the request at different stages, the two state bits are readyState and status, and ReadyState describes the 5 stages of a request by 5 status codes:
- 0-Request not sent, initialization phase
- 1-Request sent, the server has not received the request
- 2-The request was sent successfully and the server received the request
- 3-Server processing complete, start responding to requests, transfer data
- 4-The client receives the request and completes the data download, generating the Response object
The status is used to describe the server-to-request processing, 200 indicates that the request was properly responded to, 404 indicates that no resource was found, 500 represents the server internal exception, and so on.
The Ajax object can also set a timeout value, which represents the time-out. Remember: Timeout only affects readyState, not status, because timeouts only interrupt data transfer, but do not affect the server's processing results. If the timeout setting is unreasonable, it will cause the response code status to be 200, but there is no data in response, this is the case that the server responds to the request correctly, but the download of the data is interrupted by timeout.
In order to ensure the security of user information, the browser introduced the same-origin policy, the script request is limited, not allow Ajax cross-domain request server, only allow the request and the current address of the same domain server resources. But without restricting the HTML tags to send cross-domain requests, such as script, IMG, a tag, etc., you can use the label cross-domain capability to implement cross-domain requests, which is how JSONP can cross domains.
JSONP Although cross-domain issues can be resolved, only GET requests are sent, and there is no valid error-trapping mechanism. In order to solve this problem, the XMLHttpRequest Level2 the CORS specification, that is, cross-domain resource sharing. It is not a new API, but a standard specification. When the browser discovers that the request requires a cross-domain, an origin field is automatically added to the header information to indicate which source the request came from. Based on this value, the server decides whether to agree to this request.
With the rapid development of mobile, the application of WEB technology is becoming more and more complex, the principle of separation of concerns is becoming more and more important at the system design level, and XMLHttpRequest is one of the oldest interfaces of Ajax, so it is not in accord with modern system design idea. Therefore, the browser provides a new Ajax interface, that is, Fetch,fetch is based on the ES6 of Promise thought design, more in line with the principle of separation of concerns.
8, modular
Historically, the JAVASCRIPT specification has been without a module system, that is, a large program cannot be split into interdependent small files, and then assembled together in a simple way. Before ES6, in order to realize the JS modular programming, the community has developed some module loading scheme, the main has the CMD and AMD two kinds, respectively to COMMONJS and Requirejs as the representative. ES6 in the language standard level, realizes the Modularization programming, its design idea is, as far as possible static, causes the compile time to be able to determine the module dependency relation, namely compiles the load, but the CMD and the AMD is at the runtime determines the dependency, namely the runtime load.
9. node. js
node. JS is a JAVASCRIPT runtime environment based on the Chrome V8 engine, which runs independently of the browser as a hosting environment, and runs on its own as a service-side program, allowing JS programming to be brought from the client to the server for the first time, node. js The advantage on the server side is that it uses single-threaded and asynchronous I/O models to achieve a high-concurrency, high-performance runtime environment. node. js is simple to implement compared to traditional multithreaded models and can reduce resource overhead.
10, ES6
ES6 is a shorthand for ECMAScript 6.0, the next-generation standard for Javascript, which was officially launched in June 2015, and its goal is to make JS easy to develop enterprise-class large applications, so some of ES6 's specifications are moving toward Java, C # And so on the back end language standard near. In the ES6 specification, the more significant changes are in the following areas:
- New let, const command to declare the variable, and VAR, the let declaration of the variable does not have a variable promotion problem, but does not change the characteristics of JS weak type, can still accept any type of variable declaration; The const-declared variable is not allowed to change in subsequent logic, which improves the preciseness of JS syntax.
- New deconstructed assignments, rest syntax, arrow functions, and so on, are all designed to make the code look more concise, while wrapping the syntax sugar.
- The new modular mechanism, which is an important step for JavaScript to standardize, makes the front-end more convenient to implement engineering.
- New classes and inheritance concepts, with modularity, JavaScript can also achieve a highly reusable, highly scalable system architecture.
- New template string function, efficient and concise, the end of the era of stitching strings.
- Added Promise mechanism to solve the problem of multi-layered nesting of asynchronous callbacks.
Second, CSS articles
1. CSS selector
The CSS selector is a rule that matches the corresponding tag and sets CSS styles for it, commonly used class selectors, tag selectors, ID selectors, descendant selectors, group selectors, pseudo-class selectors (Before/after), sibling selectors (+~), attribute selectors, and so on.
2. CSS Reset
HTML tags will also have a default CSS style without setting any styles, and different kernel browsers may not have the same settings for this default value, which could result in inconsistent display of the same set of code on different browsers and compatibility issues. Therefore, when initializing, you need to initialize the style of the common label, make its default style uniform, this is the CSS reset, that is, CSS style reset, such as: *{margin:0,padding:0} is the simplest CSS reset
3. Box layout
The box model is an important concept of CSS and the cornerstone of CSS layout. Common box models have block-level boxes (blocks) and inline boxes (inline-block), and several properties related to boxes are: margin, border, padding, and content, The purpose of these properties is to set the relationship between the box and the box, and the relationship between the box and the content. In this case, only the vertical margins of the block-level boxes in the normal document stream will merge, and the margins between the inline boxes, floating boxes, or absolute positions will not be merged. In addition, the setting of the Box-sizing property affects the calculation of the width and height of the box.
4. Floating layout
Setting the Float property value of the element to left or right causes the element to move away from the normal document stream and to float to or from the other. Generally in the Gongge layout will be used, if the child elements are all set to float, then the parent element is collapsed, it is necessary to clear the float, clear floating method is also many, the common method is to add empty elements at the end of the element set Clear:both, more advanced to the parent container settings before/ After to simulate an empty element, you can also set the overflow property directly to Auto/hidden to clear the float. In addition to floating can achieve the layout of the palace, in-Line box (inline-block) and table can also achieve the same effect.
5. Positioning layout
Setting an element's Position property value to Relative/absolute/fixed allows the element to be detached from the document stream and offset in some reference coordinates. Where the releave is relative positioning, it is offset from its original position, the original space will not be occupied by other elements; the absolute is an absolute positioning, which is offset from its nearest location parent container as a reference, in order to locate an element. The common way is to set the parent container's poistion:relative, because the relative positioning element does not set the top and left values, does not affect the position of the element, fixed positioning, it is the browser window as a reference, The banner of the bottom hover of PC Web page can be implemented by fixed positioning, but the fixed property has compatibility problem on mobile side, so it is not recommended to use, the alternative is: absolute positioning + internal scrolling.
6. Flexible layout
The flex layout, which defines the Flex container as a flexible container, first sets its own size dynamically based on the elements in the container, and then automatically adjusts the elements in the container to fit the new size when the Flex container is applied to a size (width and height). Flex containers can also set scaling and fixed widths, and you can set the direction (landscape and portrait) of the elements in the container and whether to support the automatic wrapping of elements. With this artifact, the layout of the page can be much more convenient. Note that when set to flex layout, the float, clear, and vertical-align properties of the child elements are invalidated.
7. CSS3 Animation
CSS3 introduced two kinds of animation, namely, transition and animation,transition can let the CSS attribute value of the element change in a period of time smooth transition, the formation of animation effect, in order to make the transformation of the element more colorful, The CSS3 also introduces the Transfrom attribute, which can be used to achieve the 3D transform effect by panning (translate), rotating (rotate), zooming in (scale), and tilting (skew). Transiton also has an end event transitionend, which is triggered after the CSS completes the transition and does not trigger transitionend if the transition is removed before completion.
Animation needs to set a @keyframes to define the form in which the elements are transformed, and then make the transformation smooth by animating the function so that the animation can be set to a permanent loop presentation. Set animation-play-state:paused to pause the animation and set Animation-fill-mode:forwards to hold the animation after the last frame. In addition, can also be through the JS monitoring animation start, end and repeat the state of playback, respectively, corresponding to three events, namely Animationstart, Animationend, Animationiteration. Note that animationiteration is not triggered when the number of plays is set to 1 o'clock.
Compared with transition, the animation animation effect is more flexible and richer, there is also a difference is: transition can only actively change the element's CSS value to trigger the animation effect, and once the animation is applied, the animation begins. In addition, HTML5 also added an animation API, Requestanimationframe, which is called by JS, and according to the screen drawing frequency to change the element's CSS properties, so as to achieve the animation effect, E
8, BFC
BFC is a separate, isolated container on the page, and the child elements inside the container do not affect the outer elements. For example: internal scrolling is a BFC, when the overflow-y of a parent container is set to auto, and the child container is longer than the parent container, internal scrolling occurs, regardless of how the inner element scrolls, without affecting the layout outside the parent container, which is called the BFC of the parent container's render area. BFC can be triggered if one of the following conditions is met:
- root element, or HTML element
- The value of float is not none
- The value of overflow is not visible
- The values for display are Inline-block, Table-cell, table-caption
- The value of position is absolute or fixed
9, Sprite,iconfont, @font-face
For large sites, in order to reduce the number of HTTP requests, usually the small icons commonly used in a large map, the page load only need to request a network, and then in the CSS by setting the Background-position to control the display of the small icons required, this is the sprite diagram.
Iconfont, that is, the font icon, is to convert the commonly used icon into a font resource exists in the file, by referencing the font file in the CSS, then you can directly control the font CSS properties to set the icon style, the advantage of font icon is to save the network request, its size is not affected by the screen resolution, And you can modify the color of the icon arbitrarily.
@font-face is a module in the CSS3, @font-face can define a new font, and then you can use the CSS properties font-family the font, even if the operating system does not install the font, the page will appear normally.
10. CSS Hack
Earlier, different kernel browser to the CSS properties of the differences, resulting in inconsistent display results, such as the margin attribute in the IE6 display distance is twice times wider than other browsers, that is to say margin-left:20px; The actual display distance from the left element in IE6 is 40px, and is normal on non-IE6 browsers. Therefore, if you want all browsers to display the width of 20px, you need to add some special symbols in the CSS style, so that different browsers recognize different symbols to achieve the purpose of applying different CSS styles, this way is CSS hack, For the margin application in IE6 hack will become this:. El {margin-left:20px;_margin-left:10px}
The CSS hack compatible with the major browsers are as follows:
Third, the HTML chapter
1. BOM
The BOM is the abbreviation of the Browser object model, which is the browser object models, when a browser page is initialized, a global object is created in memory to describe the properties and state of the current window, a global object called the Browser object model, the BOM. The core object of the BOM is that the Window,window object is also the top-level object of the BOM, which contains the browser's 6 core modules:
- Document-that is, the documentation object, the rendering engine when parsing the HTML code, the corresponding DOM object is generated for each element, because of the hierarchical relationship between the elements, so the entire HTML code after parsing, will be generated by a different node of the tree structure, commonly known as the DOM tree, Document is used to describe the state and properties of the DOM tree and provides many APIs for manipulating the DOM.
- Frames -HTML sub-frame, which is a browser embedded in another window, the parent and child frames have separate scopes and contexts.
- history-in the form of a stack (FIFO), the page is accessed, the page is pushed forward, and the page returns to the stack.
- Location-Provides information about the documents loaded in the current window and some navigation features.
- Navigator -used to describe the browser itself, including the name of the browser, version, language, system platform, user attribute string and other information.
- Screen-provides the relevant properties of the browser display, such as the width and height of the display screen, the available width and height.
2. DOM system
The DOM is the abbreviation for the Document Object model, which is the standard that is common to all browsers, and the DOM maps HTML and XML documents into a tree structure of different nodes, commonly known as dom trees. Its core object is document, which describes the state and attributes of the DOM tree and provides the corresponding DOM manipulation API. With the development of history, DOM is divided into 1, 2, 3, 3 levels:
- Level 1 Dom -the proposal to become a world wide in October 1998, consists of a DOM core and Dom HTML two modules. The DOM core maps an XML-based document structure, allowing access to and manipulation of any part of the document. Dom HTML extends the DOM core by adding HTML-specific objects and functions.
- Level 2 DOM -dom Level 2 is broader because the Level 1 DOM targets only the mapping document structure. By extending the existing DOM, Level 2 DOM adds support for mouse and user interface events (DHTML long-term support for mouse and user interface events), scopes, traversal (repeating DOM documents), and cascading style sheets (CSS) through the object interface. It also extends the core of Dom 1 to support XML namespaces.
- Level 3 Dom -the DOM is further expanded by introducing a unified way of loading and saving document and document validation methods, DOM3 contains a new module called "Dom Load and save", which supports all content of XML1.0, including XML Infoset, XPath, and XML Base.
Browser support for different levels of DOM is as follows:
As you can see, the WebKit kernel browser, which is commonly used on mobile, currently supports only DOM2, and does not support DOM3.
3. Event System
Events are the basis of user interaction with the page, so far, DOM events have evolved from PC-side mouse events (mouse) to touch events (touch) and gesture events (Guesture) on the mobile side, and touch events describe every detail of the finger's operation on the screen, guesture is a more complex description of the multi-finger operation, as summarized below:
- First finger down, trigger touchstart, nothing else will happen
- Trigger Touchmove when the finger slips
- Second finger down, trigger Gesturestart
- Touchstart that triggers the second finger
- Trigger Gesturechange immediately
- Arbitrary finger movement, continuous trigger Gesturechange
- When the second finger bounces, it triggers the gestureend and will no longer trigger Gesturechange
- Touchend that triggers the second finger
- Trigger Touchstart (Dogan finger on screen, lift one, refresh global touch)
- Pop up the first finger, trigger the touchend.
The DOM2.0 model divides the event processing process into three stages, namely the event capture phase , the event processing phase , and the event bubbling phase:
- Event capture : When a user triggers a click event, the top-level object document emits an event stream, passing from the outermost DOM node to the target element node, eventually reaching the target element.
- Event Handling : Executes the handler function of the target element binding when the target element is reached. If no listener function is bound, no processing is done.
- event bubbling : The event flow starts at the target element and passes to the outermost DOM node, which is executed if a node binds the event handler.
Event-bubbling principle can be used to implement events delegate , so-called event delegation, is to add an event listener on the parent element, to listen to and handle the child elements of the event, to avoid repeating the same event for the child element binding. When the event of the target element is triggered, the event starts with the target element, passes to the outermost element, eventually bubbles onto the parent element, and the parent element is then fetched to the target element through Event.target, the benefit of which is that the parent element simply binds an event listener, It is possible to process the events of all child elements, thus reducing unnecessary event binding and improving the performance of the page.
4. HTML parsing process
After the browser loads the HTML file, the rendering engine parses the HTML tag from the top down, one step at a time, with the following general procedure:
- The user enters the URL, the browser makes a request to the server, and the server returns the HTML file;
- The rendering engine begins parsing the HTML tag and converts the label into a DOM node, generating a DOM tree;
- If an external CSS file is referenced in the head tag, a CSS file request is issued and the server returns the file, which blocks subsequent parsing;
- If the external JS file is referenced, the JS file request is issued, and the server executes the script immediately after it returns, which also blocks the parsing of the HTML;
- The engine begins to parse the contents of the body, if the tag refers to the CSS style, you need to parse the CSS file just downloaded, and then use CSS to set the style properties of the tag, and generate a rendering tree;
- If the IMG tag in the body refers to a picture resource, a request is made to the server immediately, and the engine does not wait for the picture to be downloaded, but to continue parsing the tag behind it;
- The server returns the picture file, because the picture needs to occupy certain space, will affect the later element's typesetting, therefore the engine needs to re-render this part content;
- If you run style.display= "None" in the JS script at this time, the layout is changed, and the engine needs to re-render this part of the code;
- The page parsing is complete until the HTML end tag is reached.
5. Re-painting and Reflow
When part (or all) of the render tree needs to be rebuilt because of the size, layout, hiding, etc. of the elements. This is called reflux. For example, the above IMG file loading will cause reflux, each page needs at least one reflow, that is, the first time the page loaded.
When some elements in the render tree need to update properties, these properties only affect the appearance of the element, style, without affecting the layout, such as Background-color. It is called redrawing.
As can be seen from the above, reflow is bound to cause repainting, and repainting does not necessarily cause reflux. The following actions can cause repainting and reflow:
- Add, remove elements (reflow + redraw)
- Hidden elements, Display:none (reflow + Redraw), Visibility:hidden (redraw only, not reflow)
- Move an element, such as changing the value of a top,left, or moving an element into another parent element. (Redraw + reflow)
- operation on style (different effects on various property operations)
- Another is the user's actions, such as changing the browser size, changing the browser font size, etc. (Reflow + redraw)
In addition, the transform operation does not cause repainting and reflow, and is a highly efficient rendering. This is because transform is a composition attribute, and when animating a composition property, a composition layer is created, which renders the animated element in a separate layer, which does not need to be redrawn when the element's content is not changed. The browser creates an animated frame by re-compositing.
6. Local Storage
The most primitive way to store local storage is that Cookie,cookie is a piece of text that is stored in a local browser, and the data is saved as a key-value pair, and the expiration time can be set. However, cookies are not suitable for storing large amounts of data, because each time a page is requested, the cookie is sent to the server, which makes the cookie slow and inefficient. So the size of the cookie is limited to about 4k (different browsers may be different, sub-host), as follows:
- Firefox and Safari allow up to 4,097 bytes of cookies, including the name (name), value, and equal sign.
- Opera allows up to 4,096 bytes of cookies, including: Name, value, and equal sign.
- Internet Explorer allows up to 4,095 bytes of cookies, including: Name, value, and equal sign.
In all browsers, any cookie size exceeding the limit is ignored and will never be set.
HTML5 provides two new ways to store data on the client side: Localstorage and Sessionstorage, which store data in the form of Key/value, which is permanently stored and is limited to browser sessions (session). That is, when the browser window is closed, the data in the Sessionstorage is cleared.
Localstorage storage space about 5M (different browsers may be different, sub-HOST), this equivalent to a 5M size of the front-end database, compared to cookies, can save bandwidth, but localstorage in the browser privacy mode is unreadable, An exception is thrown when the stored data exceeds the storage space of Localstorage.
In addition, H5 provides the inverse of the websql and IndexedDB, allowing the front-end to store local data in a relational database, which is relatively rare, and is not described here.
7. Browser caching mechanism
The browser caching mechanism is the mechanism for controlling file caching through fields such as Cache-control (or Expires) and last-modified (or Etag) in the HTTP protocol header.
The Cache-control is used to control how long the file is cached locally. The most common, such as the server back-up: cache-control:max-age=600 indicates that the file should be cached locally and that the duration is 600 seconds (from the time the request is made). In the next 600 seconds, if the resource is requested, the browser does not issue an HTTP request, but instead uses the locally cached file directly.
Last-modified is the time to identify the most recent update to the file on the server. On the next request, if the file cache expires, the browser passes the If-modified-since field with this time, sends it to the server, and the server compares the timestamp to determine if the file has been modified. If not modified, the server returns 304 to tell the browser to continue using the cache, or 200 if there is a change, and returns the most recent file.
Cache-control are usually used with last-modified. One to control the cache validity time, and one to query the service for updates after the cache is invalidated.
Cache-control also has a field with the same function: Expires. The value of Expires is an absolute point in time, such as: Expires:thu, 08:45:11 GMT, which indicates that the cache is valid until this point in time.
Expires is a field in the HTTP1.0 standard, and Cache-control is the new field in the HTTP1.1 standard, which, like functionality, is the effective time to control the cache. When both fields appear, the Cache-control is high-optimized.
The Etag is also the same as last-modified, which identifies the file as a field. The difference is that the Etag value is a feature string that identifies the file. When querying the server for updates, the browser uses the If-none-match field to send the feature string to the server, which is matched by the server and the file's newest feature string to determine if the file is updated. There is no update back to package 304, there is an update back to package 200. The Etag and last-modified can be used in conjunction with one or two on demand. When both are in use, the file is considered to be not updated as long as one of the conditions in the base is satisfied.
In addition, there are two special cases:
- Manually refresh the page (F5), the browser will directly assume that the cache has expired (perhaps the cache has not expired), add a field in the request: Cache-control:max-age=0, the package to the server to query whether there is a file is updated.
- Forcing the page to refresh (CTRL+F5), the browser ignores the local cache directly (there is a cache that is not cached locally), adds a field to the request: Cache-control:no-cache (or Pragma:no-cache), and the packet pulls the file back to the service.
8. History
The history of a user's visit to a Web page is usually saved in a stack-like object, the historical object, and the stack is clicked back, and the next page jumps to the stack. It provides the following ways to manipulate the forward and backward pages:
- Window.history.back () Return to previous page
- Window.history.forward () Go to the next page
- Window.history.go ([delta]) jump to the specified page
HTML5 has enhanced the history API by adding two APIs and an event, namely Pushstate, Replacestate, and Onpopstate:
- Pushstate is to add a new historical record to the history object, that is, the compression stack.
- Replacestate is the replacement of the current history in the historical object.
The Onpopstate event is triggered when you click the Browser Back button or the JS call History.back.
There is a similar event: Onhashchange,onhashchange is the old API, the browser support is high, it is used to listen to the hash changes, but can be used to do the client forward and backward event monitoring, and Onpopstate is specifically used to monitor the browser forward and backward, not only can support hash, non-hash of the same origin URL is also supported.
9. HTML5 Offline Cache
HTML5 offline cache, also known as application cache, is a buffer from the browser's cache, if you want to save data in this cache, you can use a description file (manifest file) to list the resources to download and cache.
The manifest file is a simple text file that tells the browser what to cache (as well as what is not cached). The manifest file can be divided into three parts:
- Cache MANIFEST-Files listed under this heading will be cached after the first download
- NETWORK-Files listed under this heading require a connection to the server and are not cached
- FALLBACK-Files listed under this heading provide a fallback page when the page is inaccessible (e.g. 404 pages)
Offline caching brings three benefits to your app:
- Offline Browsing-users can use them when the app is offline
- Speed-cached resources are loaded faster
- Reduce server load-The browser will download only updated or changed resources from the server.
10. Web Semantics and SEO
Web semantics is to make the appropriate label, so that the page has a good structure, page elements have meaning, can make people and search engines are easy to understand.
SEO is to understand the nature of the search engine ranking mechanism on the basis of the site for internal and external adjustment optimization, improve the site in search engines in the natural ranking of keywords, to obtain more display volume, to attract more target customers Click to visit the site, so as to achieve internet marketing and brand building goals.
Search engines through the crawler technology to get a page is a bunch of HTML tags composed of code, people can be visualized to determine what is the focus on the page, and the machine do not. However, the search engine will determine the weight of the content according to the meaning of the label, so in the right place to use the appropriate label, so that the entire page semantics, clear structure, the search engine can correctly identify the important content of the page, and give higher weights. For example H1~h6 these several tags in the SEO weight value is very high, use them as the title of the page is a simple SEO optimization.
Learn the front-end students, welcome to join the front-end learning Exchange Group
Front-end Learning Exchange QQ Group: 461593224
The context structure of Web front-end system