google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






10 thủ thuật JavaScript và jQuery để cải thiện mã nguồn của bạn Tối ưu mã nguồn ứng dụng là một công việc khá quan trọng đối với các ứng dụng lớn. Đối với ngôn ngữ lập trình JavaScript thì vấn đề này càng trở nên quan trọng hơn; bởi các ứng dụng JavaScript và ứng dụng web, đặc biệt là các ứng dụng Web 2.0 thường bị giới hạn về mặt kĩ thuật bởi khả năng xử lý của phần cứng, trình duyệt.

Tối ưu mã nguồn JavaScript trong các ứng dụng web sẽ giúp cho trình duyệt tốn ít tài nguyên để xử lí, sẽ làm cho tốc độ đáp ứng với người dùng nhanh hơn. Tuy nhiên bài viết hướng dẫn này xoay quanh các thủ thuật tối ưu JavaScript dựa trên thư viện jQuery.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

#6 – Use ID as Selector whenever possible

Selecting DOM elements using the class attribute is simpler than ever using jQuery. Even though it is simple it should be avoided whenever possible as as selecting using ID is much faster (In IE the class selector seams to loop through the entire DOM why generally it should be avoided). Selecting elements using IDs is fast because the browsers have the native getElementByID method that jQuery will use for IDs. Selecting classes still requires the DOM to be traversed behind the scene and if it is a large DOM and you make several lookups the performance impact can be significant. Let take a look at this simple html code:

<div id="main">

<form method="post" action="/">
  <h2>Selectors in jQuery</h2>

  ...
  ...
  <input class="button" id="main_button" type="submit" value="Submit" />

</form>
</div>
 
...
//Selecting the submit button using the class attribute
//like this is much slower than...
var main_button = $('#main .button');

 
//Selecting the submit button directly using the id like this
var main_button = $('#main_button');

#7 – Use Tags Before Classes

When you are selecting through tags jQuery will use the native browser JavaScript method, getElementsByTagName(). ID is still faster but this is still much faster than selecting with a class name.

<ul id="shopping_cart_items">
  <li><input class="in_stock" name="item" type="radio" value="Item-X" /> Item X</li>

  <li><input class="3-5_days" name="item" type="radio" value="Item-Y" /> Item Y</li>

  <li><input class="unknown" name="item" type="radio" value="Item-Z" /> Item Z</li>

</ul>

It is important to prefix a class with a tag name (here this is “input”) and then it is important to descend from an ID to limit the scope of the selection:

var in_stock = $('#shopping_cart_items input.in_stock');

#8 – Cache jQuery Objects

Caching an object before working with it is essential for performance. You should neverdo like this:

<li>Description: <input type="text" name="description" value="" /></li>

...
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');

$('#shopping_cart_items input.text').val("text updated");

In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.

var input_text = $('#shopping_cart_items input.text');

input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");

 
//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
 .css('border', '3px dashed yellow')

 .css('background-color', 'red')
 .val("text updated");

#9 – Bind certain jQuery functions to $(window).load event

Most jQuery code examples and tutorials instruct us to bind our jQuery code to the $(document).ready event. In many cases this is OK but since $(document).ready occurs during page render while objects are still downloading it may cause problems for some types of scripts. Functionality such as binding visual effects and animations, drag and drop, pre-fetching hidden images etc. could benefit from being bound to the $(window).load as it will ensure that all dependant elements are ready for use.

$(window).load(function(){
 // Put your jQuery functions that should only initialize after the page has loaded.
});

#10 – Use Chaining to limit selectors, make the code more simple and elegant

Because JavaScript supports chaining and because it works across line breaks you can structure your code like this. This example first removes a class on an element and then adds another to the same element.

$('#shopping_cart_items input.in_stock')
    .removeClass('in_stock')
    .addClass('3-5_days');

If needed it is really simple and useful as well to create a jQuery function that support chaining.

$.fn.makeNotInStock = function() {
    return $(this).removeClass('in_stock').addClass('3-5_days');

}
 
$('#shopping_cart_items input.in_stock').makeNotInStock().log();
iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web