google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Tăng tốc độ thực thi JavaScript: Thủ thuật và Công cụ Bài viết hướng dẫn JavaScript này cung cấp khá chi tiết các giải pháp cũng như công cụ JavaScript, ứng dụng trực tuyến để các nhà phát triển web có thể tối ưu hóa tốc độ, thời gian tải mã nguồn JavaScript của mình - một trong các yếu tố gia tăng năng suất hoạt động của website.

Các giải pháp được liệt kê từ cơ bản như cách tải tập tin JavaScript, gom và nén gọn các tệp JavaScript lại với nhau,... cho đến các giải pháp chuyên sâu tùy biến, tối ưu hóa mã nguồn JavaScript; cùng với rất nhiều tiện ích, công cụ giúp thực hiện việc tối ưu hiệu quả hơn.

Bạn vui lòng vào trang chi tiết để xem hướng dẫn đầy đủ của bài viết này, hoặc xem thêm các bài viết liên quan bên dưới:
- Tăng hiệu suất của JavaScript với trình nén của SharePoint
- 20+ công cụ hỗ trợ lập trình web tốt hơn
- Để lập trình JavaScript hiệu quả hơn
- Tổ chức mã nguồn JavaScript của bạn tốt hơn


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

Here are some tips on high perfomance Javascript I have picked up. Most
of it comes from the books High Performance Javascript
by Nicholas C. Zakas and High Performance Web Sites
by Steve Souders.

Loading

Load files at the end of the HTML page

Load the Javascript files right before the body, this will allow the
page to render without having to wait for all the Javascript files.

Group files together

With normal loading, the files are loaded sequentially. Each file will
be loaded and parsed before the next file starts to load. Merge them
together into one large file. While you are at it, you should also
minimize it. Tools to help you with this are:

Load files asynchronously

If normal loading with grouped files is not good enough, it is also
possible to load the files asynchronously. This will also allow you to
load files on demand. Tools for this are:

Variable Access

Literal values and local variables can be accessed very quickly. Array
access and member access take longer. If the prototype chain or scope
chain
needs to be traversed, it will take longer the further up the chain
the access is. Global variables are always the slowest to access because
they are always last in the scope chain.

You can improve the performance of JavaScript code by storing frequently
used, object members, array items, and out-of-scope variables, in local
variables.

DOM

All DOM manipulation is slow.

  • Minimize DOM access
  • Use local variables to store DOM references you'll access repeatedly.
  • HTML collections represent the live, underlying document, so:
    • Cache the collection length into a variable and use it when iterating
    • Make a copy of the collection into an array for heavy work on collections

Reflow and rendering

The browser contains two trees, the DOM tree and a render tree.
Whenever the DOM layout or geometry is changed the view will have to be
re-rendered. This is known as reflow.

Reflow happens when:

  • Visible DOM elements are added or removed
  • Elements change position
  • Elements change size (margin, padding, border thickness, width, height, etc.)
  • Content is changed, (text changes or an image is replaced with one of a different size)
  • The page renders initially
  • The browser window is resized

Combine multiple DOM and style changes into a batch and apply them once.
This can be done with documentFragments or by cloning the node.

// Create a document fragment
var fragment = document.createDocumentFragment(); 


// Do something with framgment 

// Append the fragments children to the DOM
document.getElementById('mylist').appendChild(fragment); 

// Clone Node
var old = document.getElementById('mylist');
var clone = old.cloneNode(true); 


// Do something with clone 

// Replace node with clone
old.parentNode.replaceChild(clone, old); 

Algorithms and Flow

Use algortithms with better complexity performance for large collections.

  • for-in loops are slower than for, while and do-while loops. Avoid
    for-in unless you need to iterate over a number of unknown object
    properties.
  • Lookup-tables are faster than multiple conditionals.
  • Recursion can be re-written with iteration if you get stackoverflow
    errors.

Strings and Regexes

Strings concatenation is quite fast in most browsers. In IE, you may
need to use Array.join.

Regular expression can be improved by:

  • Focus on failing faster.
  • Start regexes with simple, required tokens.
  • Make quantified patterns and their following pattern mutually exclusive /"[^"]*"/.
  • Use noncapturing groups. (?:) instead of ().
  • Capture text to reduce postprocessing.
  • Expose required tokens /^(ab|cd)/ instead of /(^ab|^cd)
  • Resue regexes by assigning them to variables.
  • Split complex regexes into simpler pieces.

Responsiveness

The total amount of time that a single JavaScript operation should take
is 100. If it takes longer it needs to be split up, this can be done
using timers.

Two determining factors for whether a loop can be done asynchronously
using timers:

  • Does the processing have to be done synchronously?
  • Does the data have to be processed sequentially?

// Function for processing an array in parallel

function processArray(items, process, callback) {
  var minTimeToStart = 25;

  var copyOfItems = items.concat();
  setTimeout(function() {

    process(copyOfItems.shift());
    if (copyOfItems.length > 0)

      setTimeout(arguments.callee, minTimeToStart);
    else
      callback(items);

  }, minTimeToStart);
} 

// Function for processing multiple tasks in parallel
function processTasks(tasks, args, callback) {

  var minTimeToStart = 25;
  var copyOfTasks = steps.concat();

  setTimeout(function() {
    var task = copyOfTasks.shift();

    task.apply(null, args || []);
    if (copyOfTasks.length > 0)

      setTimeout(arguments.callee, minTimeToStart);
    else
      callback();

  }, minTimeToStart);
} 

You should limit the number of high-frequency repeating timers in your
web application. It is better to create a single repeating timer that
performs multiple operations with each execution.

It is not recommended to have minTimeToStart less than 25
milliseconds, because there is a risk that the timers will fill up the
queue.

// Timed version of process array, where each version is able to
// process items from the array for up to 50 milliseconds.
function timedProcessArray(items, process, callback) {

  var minTimeToStart = 25;
  var copyOfItems = items.concat();

  setTimeout(function() {
    // (+) converts the Date object into a numeric representation
    var start = +new Date();

    do {
      process(copyOfItems.shift());
    } while (copyOfItems.length > 0 && (+new Date() - start < 50));

    if (copyOfItems.length > 0)
      setTimeout(arguments.callee, minTimeToStart);

    else
      callback(items)
  }, minTimeToStart);
} 


Newer browsers support web workers. Web workers does not run in the
UI-thread and does not affect responsiveness at all. Their environment
is limited to allow this to work. It is limited to:

  • A navigator object, which contains only four properties: appName,
    appVersion, user Agent, and platform.
  • A location object (same as on window, except all properties are read-only)
  • A self object that points to the global worker object
  • An importScripts() method that is used to load external JavaScript for
    use in the worker
  • All ECMAScript objects, such as Object, Array, Date, etc.
  • The XMLHttpRequest constructor
  • The setTimeout() and setInterval() methods
  • A close() method that stops the worker immediately

It is not possible to create a WebWorker from code. It needs to be
started with its own javascript file. You can however communicate with
it through events.

// Application code
var worker = new Worker("code.js");

worker.onmessage = function(event) {
  alert(event.data);

};
worker.postMessage("Tapir"); 

// Worker code (code.js)
//inside code.js
importScripts("file1.js", "file2.js"); // importing some files 


self.onmessage = function(event) {
  self.postMessage("Hello, " + event.data + "!");

}; 

Any code that takes longer than 100 milliseconds to run should be
refactored to use webworkers to decrease the load on the UI-thread.

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