Contents
1. If possible alternative loop Each with While or For
var arr = new Array ();
for (var i=0; i<9999; i++) {
arr[i] = 0;
}
console.time('native');
var l = arr.length;
for (var i=0;i<l; i++) {
arr[i] = i;
}
console.timeEnd('native');
console.time('jquery');
$.each (arr, function (i) {
arr[i] = i;
});
console.timeEnd('jquery');
2. Use join alternative for + when merge string
var foo = "";
foo = foo + bar;
foo += bar;
[foo, bar].join();
3. Assign value of object or funcion to variable before use in loop
for (var i in App.responsive) {
console.log(App.responsive[i]);
}
var vp = App.responsive;
for (var i in vp) {
console.log(vp[i]);
}
4. Use Observer intersectionObserver run task when in dome when visible
This Observer can use run slider, load ajax when this part visible
var el = document.getElementById(‘#slider’);
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function(entry) {
var slider = el.slick(options);
});
}, );
observer.observe(el)
5. Optimize jQuery
a. Alternative $(“document”).ready() with $()
$("document").ready(function () {
// The DOM is ready!
// The rest of the code goes here
});
Alternative with
$(function () {
// The DOM is ready!
// The rest of the code goes here
});
b. DOM manipulation
$("#element").attr("title", $("#element").text());
$("#element").css("color", "red");
$("#element").fadeOut();
Alternative with
var $el = $("#element");
$el.attr("title", $($el.text());
$el.css("color", "red");
$el.fadeOut();