JS Code guiding Principles

Source: Internet
Author: User

I. What is smooth degradation?

If the page containing JS code in the user's browser does not support JS (or disable JS), the user can still browse smoothly (the site is functioning normally, but the visual effect may be worse), then this page can be degraded smoothly

Web page can be a smooth degradation is necessary, because JS has always been a bad reputation (all kinds of ads, various pop-up windows, and even the dark things such as XSS, etc.), so there is a user group is used to disable the browser JS support, this user group may be small, But as coders should try to make their code as perfect as possible (just like nurturing their own children), we should consider this situation and give a perfect experience to all kinds of users.

If the above reasons are not enough, then there may be a little more worthy of attention: SEO, that is, search engine optimization, want to make their own site in the search results in the previous, it is necessary to do SEO, search engine searching robot can not understand the meaning of JS code, So the search robot is equivalent to a user who insists on using an old-fashioned browser (which does not support JS), obviously, this user is important

Two. How can a smooth degradation be achieved?

To smooth degradation you only need to follow one principle: Progressive enhancement

The so-called "progressive enhancement" is to use some primitive and reliable methods to achieve the most basic and important functions, first guarantee the integrity of the function, and then use some additional information layer to wrap the original page (to achieve the display effects, achieve better visual effects and user experience), even if the clothes are blocked, the function is still intact, but may not look good

The JS code and HTML code to completely separate the implementation of "progressive enhancement", HTML is the full functionality of the original layer, the external JS code is a gorgeous coat (say a bit like CSS, but it is true, JS function is very powerful, but if too dependent on the JS code to reverse the primary and secondary)

Three. What is backwards compatibility?

Backward compatibility refers to the JS code to be able to be compatible with the lower version of the DOM (some browsers may not support the latest version of the DOM, meaning that some Dom APIs will not be available), such as:

Perhaps the most common Dom APIs are these:

document.getElementById ();d ocument.getelementsbytagname ();d ocument.getelementsbyclassname (); new features in the//HTML5 DOM

However, there may be some browsers do not support these methods, or only support a portion, then the page will be due to the JS code error can not be accessed, or the page function is no longer complete

One of the previous ways to ensure backward compatibility was "browser sniffing", which was to ask the browser through the BOM: "Do you support this DOM API?" "Because there are so many browsers, a very simple JS code needs to be wrapped up by many layers of browser sniffing code, causing our code to become bloated.

Browser sniffing technology In fact still exists in the CSS, of course, CSS can not get browser features through the BOM, so the use of a relatively passive way:

/* Set the transparency to 0.75*/filter:alpha (opacity =   25);/* Support for IE browser */-moz-opacity:0.25;/* Support for FireFox browser */opacity:0.25;/* Support CHRO Me, Opera, Safari and other browsers * *

Dom has evolved so far without the need for browser sniffing to ensure backwards compatibility, and we can do this:

if (document.getElementById) {    document.getElementById ();} if (document.getelementsbytagname) {    document.getelementsbytagname ();} if (document.getelementsbyclassname) {    document.getelementsbyclassname ();//html5 new attribute in Dom}

This better approach is called "Object detection" technology, although it is still not perfect (to be perfect, unless the browser market is unification. , but it's much better than browser sniffing (at least not needing to modify the JS code because a new browser appears on the market), object detection no longer relies on the BOM, and the DOM itself detects whether the browser supports the specified DOM API

Four. JS Performance optimization Tips

    1. Try to get less JS access to the DOM
    2. Minimizing HTML markup
    3. Merging JS scripts
    4. Location of the script tag
    5. Compression JS Code

1. Before optimization:

for (var i = 0;i < document.getElementsByTagName ("a"); i++) {    if (document.getElementsByTagName ("a") [I]. GetAttribute ("title") = = "Main") {        //do something    }}

After optimization:

var elems = document.getElementsByTagName ("a"); for (var i = 0;i < elems.length;i++) {    if (Elems[i].getattribute (" Title ") = =" Main ") {        //do something    }}

Every call to the DOM method to get a tag object inside is a full search of the DOM tree, which is very expensive operation, minimizing DOM access can improve performance

2. Before optimization:

<div>    <div>        <div>            <div>                <div>                    <p>                    body                    </p >                </div>            </div>        </div>    </div></div>

After optimization:

<p> Body </p>

This example may be extreme, but it is enough to explain the problem, the HTML code should be as concise as possible (to achieve the desired performance is good)

3. Before optimization:

<scrpit src= "./scripts/a.js" type= "Text/javascript" ></script><scrpit src= "./scripts/B.js" Type= " Text/javascript "></script><scrpit src="./scripts/c.js "type=" Text/javascript "></script>

After optimization:

<scrpit src= "./scripts/all.js" type= "Text/javascript" ></script>

When the browser loads the page every time a script tag is encountered, if the label points to an external script file, you need to send a request to load the external file, if the script tag too much, this overhead will not be ignored, so you should put the JS code in an external file, with a script tag to load

4. Before optimization:

After optimization:

<body>    HTML code    <script></script></body>

That is, placing the script tag at the end of the body loads the fastest, And it does not affect the triggering of events such as Window.onload, as to why it is placed in this position the fastest, probably with the browser to explain the order of the HTML code (first load the head section, if the head is too large, will cause the user to wait for a long time still see the body content)

5. Before optimization:

var elems = document.getElementsByTagName ("P"); for (var i = 0;i < elems.length;i++) {    //do something}

After optimization:

var elems=document.getelementsbytagname ("P"); for (Var i=0;i<elems.length;i++) {}

Well, yes, the optimized code is not readable, but it's not easy to read, but it's small enough to make the external file smaller and, of course, improve performance.

P.S. This job has a special tool for us to do, like Jsmin and so on.

Reference: JavaScript DOM variable programming art

JS Code guiding Principles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.