This is the second day of my participation in Gwen Challenge

Responsive user interface

Would you rather experience a web page with a smooth interaction, or a page that clicks and then responds a little later (like a school page)?

Good JavaScript writing method can improve the speed of page interaction response, the following knowledge can be understood and applied

Browser UI thread

The process used to execute JavaScript and update the user interface is often referred to as the “browser UI thread”

UI threads work based on a simple queue system, where tasks are stored until the process is idle. Once idle, the next task in the queue is extracted and run again.

Example analysis:

<button onclick="handleClick()"> button < / button ><script>
    function handleClick() {
        var div = document.createElement("div");
        div.innerText = "Click the button.";
        document.body.appendChild(div)
    }
</script>
Copy the code

This is an example of clicking a button to trigger the handleClick method

When the button is clicked, it triggers the UI thread to create two tasks and add them to the queue

Two tasks:

  1. Update the button style to represent the UI being clicked
  2. Execute JavaScript, including the code in the handleClick method

In fact, when the handleClick method is executed, a new div element is added to the end, which causes another UI change

Most browsers stop queuing new tasks to the UI thread while JavaScript is running, so JavaScript tasks must end as soon as possible to avoid adverse effects on the user experience




Browser Restrictions

Browsers limit the running time of JavaScript tasks

This restriction is necessary to ensure that some malicious code cannot lock a user’s browser or computer through intensive operations that never stop

These restrictions fall into two categories:

  • Call stack size limit
  • Restrictions on long-running scripts

Long-running script limits are also known as out-of-control script timers

The idea is that the browser keeps track of how long a script has been running and terminates it when it reaches a certain limit, presenting the user with a long, unresponsive dialog.


Chrome:


The timer

JavaScript timers can interact with UI threads to help break scripts that take longer to run into shorter pieces

Accuracy of timer

JavaScript timer delays are usually not particularly precise, varying by a few milliseconds, so timers cannot be used to measure the actual time.

On Windows, the timer resolution is 15.6ms. This was deliberately set by Microsoft, who felt that setting a lower precision would be too costly, so a timer with a delay of 15.6ms would be converted to 0 or 15 depending on the last system time refresh.

Setting the timer delay to less than 15 will lock Internet Explorer. Therefore, you are advised to set the minimum delay to 25 to ensure a delay of at least 15 milliseconds. ———— This is why setTimeout and setInterval timing methods are almost always written with a delay longer than a certain number of milliseconds.





Web Workers

Since the birth of JavaScript, it has been single-threaded. But JavaScript also has multithreading, thanks to Web Workers!

Here comes the reference link:

  • Web Workers API in MDN
  • Introduction of Worker in MDN
  • Ruan Yifeng god’s blog

Using Web Workers, a Web application can run a scripted operation in a background thread independent of the main thread.

As you can understand, the Web Workers API introduces an interface that allows code to run without consuming the browser UI thread. Each new worker runs code in its own thread, which means that the code run by the worker does not affect the browser UI, nor does it affect the code run by other workers.




Worker operating environment

Worker interface is a part of Web Workers API, which refers to a background task that can be created by script and can send and receive information to its creator during task execution. To create a Worker, simply call the Worker(URL) constructor, whose parameter URL is the specified script. Workers can also create new workers, of course, all workers must be of the same origin as their creator

  • Due to theWeb WorkersThe UI threads are not bound, which means they can’t access many of the browser’s resources
  • Part of the reason JavaScript and UI share the same process is that they are frequently accessed by each other, so losing control of tasks can lead to a poor user experience
  • Web WorkersModifying the DOM from an external thread can cause user interface errors, but each Web WorkersEach has its own global runtime environment
    • A Navigator object contains only four properties: appName, appVersion, userAgent, and Platform
    • A location object (same as window.location, but all properties are read-only)
    • A self object that points to the global worker object
    • An importScripts() method that loads external JavaScript files used by the Worker
    • All ECMAScript objects such as Object, Array, Date, etc
    • XMLHttpRequest constructor
    • SetTimeout () and setInterval() methods
    • A close() method can stop the Worker immediately

Since Web Workers are different global operating environments, we need to create a completely independent JS file, which contains the code running in Worker. Then in the main process new Worker(Web Workers code path)

 var worker = new Worker('code.js')
Copy the code

Once executed, this code creates a new thread and a new Worker runtime environment. The file will be downloaded asynchronously, and the worker will not start until the file is downloaded and executed


The sample

Basic examples:structure

In the HTML

<body>
    <button onclick="clickHandle()">Click on the</button>
    <script>      
        let worker = new Worker('code.js')
        console.log(worker)
        function clickHandle() {
            // Send an object data to the worker object
            worker.postMessage({
                msg: 'Send data in'})}</script>
</body>
Copy the code

In the code. Js

console.log("The worker started!")
// Receive the transmitted data
onmessage = function(e) {
    console.log(e)
}
Copy the code

Effect achieved

Pay attention to

The software I use here is VS Code. If you open HTML in this way, you will not find the JS file of the Web worker because of the same origin policy mentioned above.

The following error may be reported

So you need to run it on a Server, and for simplicity I recommend using a plugin called Live Server.

This plug-in is a small server with real-time loading capability and can be used to hack HTML/CSS /javascript, but not to deploy the final site.

When running the index.html file


The practical application

Web Workers for long-running scripts that deal with pure data or are unrelated to the browser UI.

Some tasks that can benefit from working with Web Workers:

  • Encode/decode large strings
  • Complex mathematical operations (including image or video processing)
  • Large array sort




section

  • JavaScript tasks should not exceed 100 milliseconds, as long running times can cause significant delays in UI updates
  • Timers can help you break down long-running scripts into a series of smaller tasks
  • Web WorkersIs a feature supported by newer browsers and is a multi-threaded solution for JavaScript

The more complex a Web application becomes, the more important it becomes to manage UI threads. JavaScript, however important, should not interfere with the user experience