Tip 1: setTimeout.
Application case: For example, if you want to execute a function loop 10 times, what should you do? In the past, it was usually setInterval first, and then clearInterval. Tip 1 is to overcome this problem
(function () {
var i = 0;
function job() {
console.log(i );
if (i < 10) {
setTimeout(job, 1000);
}
}
job();
})( ; >
Copy code
}
})();
Why is this method efficient? ?
One: One parameter l=arr.length is missing;
Two: The thing in the middle of the for statement has one less calculation. In the past, it was for(i=0;i
, which naturally requires more calculations
Tip 3: Efficient assignment Application case: Abandon the traditional if judgment assignment
Copy code
The above code will magically tell you that ret will be true. It is efficient and does not use if(i!==1) After assigning value
Skill 4: Powerful short attr
Application case: setAttribute, getAttribute. This method can not only set standard attributes, but also set arbitrary attributes, and is compatible
Copy code
ret = elem.getAttributeNode(name);
if (!ret) { //ie6 7 illegal attribute setting, through here you can set
ret = document.createAttribute(name);
elem.setAttributeNode(ret);
}
ret.nodeValue = value "";
} else {
elem.setAttribute(name, value);
}
return elem;
} else { //ie6 7 has attributes that are not easy to obtain
ret = elem.getAttribute(name);
fixIe = elem.getAttributeNode(name).nodeValue;
ret = ret ? ret : fixIe ? fixIe : undefined;
return ret;
}
}
How to test the above method?
attr(document.getElementById("test"), "classxx", "xx")
alert(attr(document.getElementById( "test"),"classxx"));
Tip 5: getElementsByClassName.
Application case: In the past when js had no framework, everyone imitated this method. Let’s see how I can imitate it efficiently today. Come on. This is indeed a classic code for js beginners
Copy the code
root.getElementsByClassName(cls) : help("*", cls, context);
}
var help=function(tagName,cls,context){
var root= context || document,
ret=[],elems,i,
rcls=new RegExp("^|\s " cls "\s |$");
elems = root.getElementsByTagName(tagName || " *");
for(i=elems.length;i--;){
if(rcls.test(elem[i].className)){
ret.push(elems[i] );
}
}
return ret;
}
})();
The above js obscene techniques are quite practical, provided that You don’t have to use other people’s js frameworks, use native code that is premised on creating efficiency.
It’s still the original sentence of nothing for js code enthusiasts. Thank you for your support. If you think it’s well written, you can upvote it or send the link to your friends.