Analysis and Optimization of JavaScript code for the lucky draw (I)
Recently, a special Lucky Draw effect plug-in for "marquee" was created in the project. I have already shared my previous article.html
Andcss
. This article mainly shares some knowledge about JavaScript. When I was writing this article these days, I also reconstructed my code.
Here we mainly write our own optimization process. As the saying goes:
The progress of a programmer begins with dissatisfaction with his own code.
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 isrem
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')
Just in$()
Specify the class or ID of the Dom node you need or use the attribute selector.
After viewing the jQuery documentation$()
There will be such a description:
jQuery([selector,[context]])
The most important thing is to look atcontext
(It is also a very useful parameter that is the easiest to ignore 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 betterdocument
Search is much faster.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? Thiscontext
The parameter determines the row.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.
But sometimes we want to use some nativeArray
Method or attribute of the object. Let's look at a simple example:
The code running result in the figure shows that the jQuery object is not used.reverse
Method.Althoughtest
Is an array.
So what can we do to make jQuery objects use nativeArray
What about object methods?
4.1 Use prototype chain extension
For example, the following code:
JQuery. prototype. reverse = function () {// some operations}
Useprototype
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:
Array. from ()The method can convert an array object or iteratable object to 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
BecausesetTimeout()
AndsetInterval()
These two functions have the same implementation mechanism in JavaScript.setTimeout()
Verify
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
We can see from the above results that when we are usingsetInterval()
AndsetTimeout()
In the callbackthis
When,this
The scope of has changed and pointswindow
.
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 runaaa()
The task will not be executed immediately after one second.ccc()
, But will waitbbb()
Execute after executionccc()
At this time, the main thread has finished running for 4 s.