JavaScript code Analysis and Optimization for the example of the lantern draw activity (1 ).

Source: Internet
Author: User
Tags javascript array

JavaScript code Analysis and Optimization for the example of the lantern draw activity (1 ).

Recently, I have made a project in which I want to achieve the lucky draw effect. To achieve this function, I mainly use js-related knowledge. If you are interested, read the full text.

Before you begin, let's take a look at the two questions and several knowledge points missed in the previous article, which need to be used in the process of self-reconstruction:

1. Problems with 1px pixel lines on mobile terminals

The design draft for the mobile page that the designer gave me is a double image. In principle, when writing a webpage, the actual size of all objects is divided by 2. But what about 1 pixel lines?

Let's take a look at the two figures. The effects of the design draft are as follows:

 

Actual display results in Samsung S4:

 

We can see that the 1px line is not displayed at this time. This problem is related to the screen pixel density of S4 mobile phones. There are many articles about the relationship between the pixel density and the 1px line on the screen. You can search for them by yourself. The solution here is not to process the 1px line. Write as much as possible. Even if my basic unit is rem, It is not another unit.

{position: absolute;width: 13rem;height: 9.2rem;border:1px solid #000;}

2. Differences in the success rate between pc browser and mobile browser

Let's take a look at a piece of code:

$('[node-type=row-a').find('div');

Obviously, the selector I use has a syntax error. But what are the results of running the code in the browser? See:

Obviously, even if I have a syntax error for the property selector, PC-side browsers can correctly parse it. However, on the mobile phone end, this method cannot be correctly parsed and the Code cannot run.

So pay attention to some small details when writing code...

3. Use of selector in jQuery

The most frequently used selector in jQuery or Zepto is written as follows,

$('div.testClass')

Write the class or ID of the Dom node you need in $ () and use the attribute selector.
When viewing the jQuery document, $ () will be described as follows:

jQuery([selector,[context]])

The most important thing is to look at the description of context (which is also the most easy to ignore but very useful parameter in our daily use:

By default, if the context parameter is not specified, $ () searches for DOM elements in the current HTML document. If the context parameter is specified, such as a DOM element set or jQuery object, then it will be searched in this context. After jQuery 1.3.2, the returned element order is equivalent to the order in which the elements appear in the context.

When I first started learning JavaScript, I heard that DOM operations are very poor in browser performance, and DOM traversal also affects program performance.
If we look for the required Dom in the specified range, will it be much faster than searching the entire document. In addition, when we write web Components, components on a page may appear many times. How can we determine which component we want to operate? The context parameter determines the rows. For more information, see wow...

4. Convert jQuery objects to Arrays

When I first started learning jQuery, I saw a sentence in a book:

The jQuery object is a JavaScript array.

In addition, JavaScript objects are converted to jQuery objects, while jQuery objects are converted to js objects. I will not introduce these basics too much.
However, sometimes we want to use methods or attributes of native Array objects on jQuery objects. Let's look at a simple example:


The code running result in the figure shows that the reverse method is not used on the jQuery object. Although test is an array.
So what can we do to make jQuery objects use the native Array object method?

4.1 Use prototype chain extension

For example, the following code:

JQuery. prototype. reverse = function () {// some operations}

When prototype is used to expand the method, we always think that the disadvantage is that it may pollute existing methods on the prototype chain. Also, you need to find the prototype chain when accessing the method.

4.2 Add the objects in the jQuery object to the array

See the following code.

var test = $('div.test');var a=[];$(test).each(function(){a.push($(this));});a.reverse();

In this way, you can flip the jQuery object.

4.3 Use the from () method of the Array object

This method is also used in the compilation of plug-ins. Take a look at the description of this document:

The Array. from () method can convert an Array object of the class or an Iterated object into a real Array.
I personally feel that this code is concise. I do not know whether the performance is affected. Continue with the following code:

var test = $('div.test');var a= Array.from(test);a.reverse();

5. Influence of setInterval () and setTimeout () on Program Performance

Because the setTimeout () and setInterval () functions have the same implementation mechanism in JavaScript, only setTimeout () is used for verification.

Let's look at the two sections of code.

var a ={test:function(){setTimeout(this.bbb,1000);},bbb:function(){console.log('----');}};a.test()

The output result is as follows:

See what the following code outputs

var a ={test:function(){setTimeout(function(){console.log(this);this.bbb();},1000);},bbb:function(){console.log('----');}};a.test();

When running this code, the code reports an error

From the above results, we can know that when we use setInterval () and setTimeout (), when we use this in the return, the scope of this has changed, and points to the window.

SetTimeout (fn, 0) indicates that a task is executed at the earliest available idle time in the main thread, that is, as early as possible. It adds an event at the end of the "task queue". Therefore, it will be executed only after the synchronization task and the "task queue" existing events are processed.
This means that after setTimeout () is set, it may not be executed immediately after several seconds, but will be executed after all the tasks in the main thread are processed, so there is a phenomenon that "wait" exceeds the set time. At the same time, there will also be other setTimeout () in the asynchronous queue, which will wait until the previous execution is complete and then execute the current one.

Let's look at a Demo:

setTimeout(function bbb(){},4000);function aaa(){setTimeout(function ccc(){},1000);}aaa();

If the above Code is run, after aaa () is executed, the ccc () will not be executed immediately after one second, but will wait until bbb () is executed and then run ccc () at this time, the main thread has finished running for 4 s.

The above content is about code parsing and optimization of the example code for the lantern draw in JavaScript (1). I will continue to share with you the code parsing and optimization of the example code for the lantern draw in JavaScript (2 ), if you are interested, stay tuned.

Articles you may be interested in:
  • Javascript single-line text scroll up
  • Javascript code for hover and zoom in
  • Js marquee code (self-written)
  • Javascript text box walking and running lantern effect code sharing
  • JavaScript code for implementing the text effect of the running lantern in the status bar
  • Example of a javascript Lucky Draw
  • Analysis and Optimization of the code of the example for the lucky draw with JavaScript (2)

Related Article

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.