JAVASCRIPT Articles
0. Basic Grammar
The basic JavaScript syntax includes: variable definition, data type, looping, selection, built-in objects, and so on.
Data types are string,number,boolean,null,undefined,object and so on. Where String,number and Boolean are the underlying types, null and undefined are two special types in JS, and object is a reference type.
JavaScript can use typeof to determine the underlying data type, but cannot accurately determine the reference type, so there is another way, that is, the object's ToString, about the data type and its judgment can refer to the following blog: data type detailed and four ways to Judge JS data types
JS commonly used built-in objects have date, Array, Json,regexp and so on. In general, date and array are most frequently used, JSON can serialize and deserialize objects and arrays, and one effect is to implement deep copies of objects .
RegExp is the regular expression, which is a powerful tool for processing strings. An introduction to data types and regular expressions can be found in the blog: ES5 9 APIs and JS Regular expression refinement with array enhancements
1. Function prototype chain
Although JavaScript does not have an inheritance concept, JavaScript establishes prototype object prototype in function functions, and constructs a prototype chain from the top to the bottom, from the functional object to the main line.
In simple terms, a variable lookup mechanism is established, and when a 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 returned if it is not undefined.
Therefore, we often use the function of the prototype mechanism to achieve JS inheritance. For the function prototype chain, refer tothe blog: JS prototype object and 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. There is no block-level scope in JS, only the function scope, so there is another strange phenomenon in JS, that is, variable promotion . For an introduction to scopes, refer to the blog: scope and scope chain of functions
3. function pointer this
This is present in the function, which points to the object that the function is called at run time . In the actual project, there are more pits to encounter this, so a deep understanding of this is needed.
The function object also provides methods such as call, apply, and bind to change the this point of the functions, where call and apply are actively executing functions, and bind is typically used in event callbacks, while the difference between call and apply is only the way the parameters are passed. For call,apply and bind users please refer to the blog: detailed js call,apply and bind
4. Constructor new
The function in JS can be a constructor and can be called as a normal function, when using new to create an object, the corresponding function is a constructor, called by the object is a normal function.
Common functions are created in three ways: explicit declaration, anonymous definition, new function (), and so on.
When creating a new object through new, JS bottom 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. For more information about new, please refer to the blog: Understanding the new operator in JS
5. Closed Package
Closures are actually an active block of code that is special in that it is possible to persist local variables without polluting the global variables and to form a separate execution process, so we often use closures to define components. For a description of closures, please refer to: Dry Goods sharing: let you learn to divide the Minutes JS closed bag
6, single-threaded and asynchronous queues
SetTimeout and SetInterval are JS built-in two timers, the use is very simple, but the principle behind the two methods is not simple.
We know that JS 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 (function), the main thread will form a global execution environment, the execution environment uses the stack of the way to execute the task to be executed sequentially.
However, there are some tasks in the browser are very time-consuming, such as HTTP requests, timers, event callbacks, etc., in order to ensure that the performance of other tasks are not affected,JS in the execution environment to maintain an asynchronous queue (also called a worker), and put these tasks queued to wait for, The timing of these tasks is not deterministic, and it is only after the task execution of the main thread has completed that the tasks in the asynchronous queue are checked for execution. This is why settimeout (fn,0) always waits for the last execution. For single-threaded and asynchronous queue issues, please refer to:setTimeout (0)
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. To prevent XSS attacks, the browser restricts Ajax, and does not allow Ajax to request servers across domains, only to access URLs under the current domain name.
Of course, if you are sure that your site does not have cross-domain risks, you can proactively open cross-domain requests on the server side. It can also be implemented directly through Cors or JSONP.
JSONP is the use of scripting (script) cross-domain capabilities to emulate Ajax requests.
Cors is a universal standard, with the name "cross-domain resource sharing" (cross-origin resource sharing). It allows the browser to issue XMLHttpRequest requests to cross-origin servers, overcoming the limitation that Ajax can only use the same origin. For a description of cors, please refer to: cross-domain resource sharing CORS detailed
8. Dom Object Document
The Document object holds the entire Web page DOM structure, and all elements on the page are eventually mapped to a DOM object. Document also provides a number of APIs to find specific DOM objects, such as Getelementbyid,queryselector and so on.
9. Events System Event
Events are the basis of user interaction with the page, so far, DOM events have evolved from PC-side mouse events (mouse) to touch-and gesture events (Guesture) on mobile
Because the DOM structure can be nested multiple layers, two kinds of event streams are derived: Event capture and event bubbling, which are most commonly used. The event bubbling mechanism can be used to implement many functions, such as page click Statistics. For an introduction to the two event streams, refer to: event bubbling and capturing
In addition, events such as onload/ondomcontentloaded, Onscroll, onvisibility, and Onhashchange are built in when the page is initialized, scrolled, hidden, returned, and so on, if you want to capture these events, The binding needs to be done through addeventlisener/attachevent.
10. Global Object Window
In JS, when a section of JS code is loaded in the browser execution, the JS engine in memory to build a global execution environment, the role of the execution environment is to ensure that all functions can be executed in the correct order , and the Window object is a global object in this execution environment, There are many operations APIs and objects built into the Window object, one of which is the document object. For a description of JS execution environment, please refer to the blog: in- depth understanding of JS execution Details
CSS Articles
CSS is a language used to decorate HTML.
1. Selector
There are many kinds of CSS selectors, such as class selector, tag Selector, id selector, descendant selector, group selector, pseudo class selector (before/after), brother selector (+~), attribute selector, and so on.
2. Positioning
Positioning is generally relative positioning (relative), absolute positioning (absolute), fixed positioning (fix), relative and absolute on the mobile side of the most, fixed on the mobile side has compatibility issues, it is not recommended to use, Replacing the fixed solution on the mobile side is absolute+ internal scrolling.
3. Floating
setting float to left or right causes the element to move out of the document stream, floating to or away. Generally in the layout of the palace pattern 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:auto/hidden directly. In addition to the float can be implemented in the palace mode, in-line box (inline-block) and table can also.
4. Box Model
The box model is the most 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 of the key properties of the box include margin, border, padding, and content, These elements can set the relationship between the box and the box and the relationship between the box and the content. Another problem is to calculate the size of the box, it should be noted that the setting of the Box-sizing property affects the width and height of the box. Margin merging is only possible with the vertical margin of the block box in the normal document flow. Margins between inline boxes, floating boxes, or absolute positioning are not merged.
5. Flex Layout
The Flex layout container is a telescopic container, where the container itself will be set to its own size dynamically, and then when the Flex container is applied to a size (width and height), the elements in the container are automatically adjusted to fit the new size. 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.
6, Transition (transition) and transform (rotation)
The transform can be used to pan (translate), rotate (rotate), zoom out (scale), tilt (skew), and so on, and transition make CSS property values (including transform) smooth transitions over time. You can use transition and transform to achieve a sliding page transition.
7, animation Animation
Animation first need to set an animation function, and then in this animation to change the elements of the CSS properties of the changes, the animation can be set to a permanent loop presentation. Compared with transition, the animation animation effect is more flexible and richer, there is a difference between the two: transition can only change the CSS value of the element to trigger the animation effect, and once the animation is applied, it starts to perform the animation.
8. Sprite Diagram
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 Background-position to control the display of the small icon.
9. Font icon Iconfont
The so-called 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, and then you can directly control the font's CSS properties to set the icon style.
HTML article
1. Web Semantics and SEO
HTML regular tags have html,head,body,div,span,table,ul,ol,dl,p,b,h1~h6,strong,form,input,img,em,i and so on, in addition HTML5 also added a lot of semantic tags, Like Header,acticle,aside,section,footer,audio,radio and so on.
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 the page is a bunch of HTML tags composed of code, people can be visualized to determine what is the focus of 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.
2. Page rendering mechanism
Page rendering is the process by which the browser's rendering engine displays HTML code in a browser window based on rules defined by CSS. The approximate working principle is as follows:
The user enters the URL, the browser makes a request to the server, and the server returns the HTML file;
The rendering engine starts loading the HTML code and converts the tags in the HTML into DOM nodes, creating a DOM tree;
If an external CSS file is referenced, a CSS file request is issued and the server returns the file;
If an external JS file is referenced, a JS file request is issued, and the server returns to the file and starts running;
The rendering engine continues to load the portion of the code in the HTML and begins parsing the CSS file that was previously returned, then calculates the style of the node based on the CSS selector and creates the rendering tree;
Recursive call from the root node, calculate the size of each element, position, etc., to each node should appear on the screen of the exact coordinates;
If a picture resource is referenced in the body, a request is made to the server immediately, and the rendering engine does not wait for the picture to be downloaded, but to continue rendering the following code;
The server returns a picture file, because the picture occupies a certain area, affecting the layout of the later paragraphs, so the engine needs to go back to render this part of the code;
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;
Until now, the page has been rendered.
3. Redraw 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.
Operations that 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,transform, 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)
4. 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 front-end page of the database, compared to the cookie 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.
5. 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.
6. History routing Mechanism
The history of a user's visit to a Web page is usually saved in a stack-like object, which is the historical object, which is clicked back to the stack and jumps to the next page. It provides a number of 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.
When you click the browser Back button or JS call History.back will trigger the Onpopstate event , with a similar event: Onhashchange.
Onhashchange is the old API, browser support is high, it is used to monitor the hash changes, but can be used to do the client forward and backward event monitoring, onpopstate is specifically used to monitor the browser forward and backward, not only can support hash, Non-hash same-origin URLs are also supported.
7. 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– the files listed under this heading provide a fallback page when the page is inaccessible (for example, 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.
8. Canvas and SVG
Canvas uses JavaScript to draw 2D graphics. The Canvas is rendered per pixel. In the Canvas, once the drawing is drawn, it will not continue to get the attention of the browser. If its position changes, the entire scene also needs to be redrawn, including any objects that might have been overwritten by the graphic.
SVG is a language that uses XML to describe 2D graphics. SVG is based on XML, which means that every element in the SVG DOM is available. You can attach a JavaScript event handler to an element. In SVG, each drawn shape is treated as an object. If the properties of the SVG object change, the browser can automatically reproduce the graphic.
Compared to canvas and SVG, canvas is more dependent on resolution, does not support event handlers, is weak in text rendering, is more suitable for intensive games, many of which are drawn frequently, while SVG is more suitable for applications similar to Google Maps with large rendering areas.
Front-end JavaScript and HTML summary