Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

Recently in browsing articles, see a dynamic performance grading strategy in the client’s practice 】 【 article, it tells the story of how to use the equipment to collect information, such as memory, CPU, power and speed information of the performance level and the business component again according to the level of performance analysis to execute the corresponding to the performance of the strategy plan, such as: When you use OSS services to store image resources, you can dynamically modify oss parameters to return higher resolution images, or lower the image resolution, with a better overall performance rating.

This article sorted out how to monitor the corresponding data in the browser environment.

System monitoring

1. The CPU to monitor

CPU is rarely mentioned in browsers. It is often referred to as js task execution delay, which is the browser’s event loop, message queue, macro task, micro task, delay queue and so on. If the current task is blocked, such as executing a time-consuming task, then subsequent events must be delayed because js execution is single threaded. The Web Api also doesn’t provide a way to get the CPU, so how do we get it? In other words, how to calculate the js task execution delay time per unit time, which can also reflect the current JS execution efficiency, which is also what we want.

Look at this code:

let data = [],t;
let getNow = () = >new Date().getTime()
const cpuTimer = setInterval(() = >{
   t && data.push(getNow()-t);
   t = getNow();
},500);
Copy the code

Ideally, the output data value for the example would be [500,505,508,506… It fluctuates within a certain range. When the fluctuation is small, it can be considered that the current JS task has high execution efficiency and no blocking JS task. However, when the fluctuation threshold exceeds, for example, 50, we can identify the js task that performs energy consumption.

2. Monitor memory

Performance Provides Performance information about the current page, for example, the Performance Timeline API, Navigation Timing API, and User Timing API. A non-standard extension has been added to Chrome: performance.memory, which provides information about memory usage.

Const {// Total allocated heap size, in bytes totalJSHeapSize, // Js heap currently in use, in bytes usedJSHeapSize, // Maximum heap size available for context, JsHeapSizeLimit} = performance.memoryCopy the code

For usage, you can monitor the browser’s memory usage threshold and alert if it is exceeded:

(()=>{// Allow Max. 50MB const MAX_MEMORY_ALLOW = 50 * 1048576; Const MAX_MEMORY_PERCENT_ALLOW = 90; RequestAnimationFrame (function monitor () {if (performance. The memory. UsedJSHeapSize > MAX_MEMORY_ALLOW) {/ / high p Use more than 50 MB} the if (performance. The memory. UsedJSHeapSize > (MAX_MEMORY_PERCENT_ALLOW / 100) * the performance in the memory. JsHeapSizeLimit) {/ / Alarm: Usage exceeds 90%}})})()Copy the code

3. Network monitoring

Network monitoring is to obtain the current time segment of the network speed, when the network speed is good, response to higher resolution resource pictures. The Web API does not provide the same capabilities. To obtain the time network speed, you can calculate the network speed by loading the resource file from the server through the intermittent time.

function getNetworkSpeed(){ const startTime = getNow(); Open ('GET', 'server resource file, ') xhr.onload = function(){const duration = (getNow() - startTime)/1000; // Convert to M const size = xhr.getresponseHeader (' content-length ')/1024/1024; // Download speed: * Mb/s const speed = (size/duration).tofixed (2)} xhr.send()}Copy the code

4. Electric quantity monitoring

Power monitoring is mainly to obtain the low power status of the equipment, and reduce the frequency of some cyclic execution tasks when the system power is low, so as to save power. Or automatically save some data on the page when the battery is down to a certain level to prevent user data loss. It can effectively reduce users’ electricity anxiety.

The Web API provides the Battery Status API, which provides two interfaces:

  1. BatteryManager: Provides information about the battery level of the system
  2. Navigator.getbattery () : Returns a Promise object, and the resolve argument is a BatteryManager object

Here’s how to use it

function updateBatteryStatus(battery) {  
   // A Boolean value indicating the charging status of the battery
   document.querySelector('#charging').textContent = battery.charging ? 'charging' : 'not charging'; 
   // Indicates the power level of the battery, from 0 to 1
   document.querySelector('#level').textContent = battery.level;  
   // Indicates how long it will take for the battery to run out, in unit (s)
   document.querySelector('#dischargingTime').textContent = battery.dischargingTime / 60; 
} 

navigator.getBattery().then(function(battery) { 
   // Update the battery status initially when the promise resolves ...   
   updateBatteryStatus(battery); 
   // .. and for any subsequent updates.
   battery.onchargingchange = function () { 
     updateBatteryStatus(battery); 
   }; 
   battery.onlevelchange = function () { 
     updateBatteryStatus(battery); 
   };      
   battery.ondischargingtimechange = function () {         
     updateBatteryStatus(battery); 
   }; 
});
Copy the code

Use this API with caution, as it is not compatible and the Battery Status API will be removed from the Web standards in the future. Compatibility:

conclusion

System environment monitoring in the browser due to the existence of compatibility, or web applications in the performance of granularity is not so demanding, so the use of such scenarios is relatively few, right as an understanding, expand the field of vision.