In addition to good design and elegant interaction, loading speed is the most important thing for a website to attract more traffic and increase user engagement. No user is willing to wait, even for a second, and they may not come back. This is where performance tuning becomes very important.

Performance optimization program has to mention yahoo military rules, the list summarizes a lot of attention and solutions for everyone to refer to. While Yahoo’s catch-22 doesn’t cover all performance optimizations, it’s worth mentioning that event optimizations — throttle and debounce — are common in practice

background

If we bind the DOM to the onScroll event, we can easily trigger dozens of events per second while using the trackpad, scrolling the scroll wheel, or dragging the scroll bar. Even more dramatic is the performance on the phone: a slow swipe can trigger events as many as 100 times a second. At such a high execution rate, your callback function is under a lot of pressure, and even more painful is that the function firing frequency is too high and the response speed may not keep pace with the firing frequency, resulting in delays, false death, or stalling. That’s a very bad experience. Don’t think of this as a minor problem, but the famous Twitter site had this problem when scrolling down the Twitter stream became slow and sluggish. The scroll event is associated with an expensive function.

Functions with anti-shake and throttling become especially useful,why? Since we add a layer of control between the event and the function execution, this layer controls whether the function executes. Note that we can’t control how often DOM events fire.

With that background, let’s talk about event throttling and event stabilization respectively

Common: limit the frequency of function execution, to achieve the purpose of optimization

Difference:

  • Event throttling

    The solution is to allow a function to execute only once in x milliseconds. The main difference with anti-shock is that throttling ensures that it executes at least once in x milliseconds. The latest simple example is 🌰 : every 200ms check the scroll position and trigger the page load

  • Events offer

    The method is to combine events that fire very frequently (such as key events, resize) into a single execution

You can also create your own Debounce/Throttle wheel or copy it from any blog post. I’m using Lodash directly here (or underscore can also be used). Use the LoDash custom build tool to generate a compressed library containing only the _. Debounce or _. Throttle methods, using the following simple command:

npm i -g lodash-cli
lodash-cli include=debounce,throttle
Copy the code

Ok, here is the event throttling 🌰 for everyone to see

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
      body {
        background: #e1e1e1;
        margin:0 auto;
        max-width:600px;
        padding:12px;
      }
      .item {
        height:120px;
        width:100%;
        margin-top:50px;
        padding:20px;
      }
      .color-1 { background: #9BFFBB}
      .color-2 { background: #B9C6FF}
      .color-3 { background: #FFA3D8}
      .color-4 { background: #FF8E9B}</style> </head> <body> <h1> This is an event throttling of 🌰 ha ha da </h1> <div class="item color-1">Block 1</div>
<div class="item color-2">Block 2</div>
<div class="item color-3">Block 3</div>
<div class="item color-4">Block 4</div>
</body>
<script src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js'></script>
<script>
    $(document).ready(function(){
    // Check every 200ms the scroll position
    $(document).on('scroll', _.throttle(function(){
      check_if_load_more();
    }, 300));

    function check_if_load_more() {
      BottomPixelsFromWindow = 0 + $(document).height() - $(window).scrollTop() -$(window).height();
      if (BottomPixelsFromWindow < 200){
        $('body').append($('.item').clone()); }}}); </script> </html>Copy the code

Here’s another one:

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
      body {
        background: #e1e1e1;
        color: white;
        margin:0 auto;
      }
      .left-part,
      .right-part {
        padding:1%;
        margin:0;
        width:45%;
        float:left;
        min-height:100vh;
        text-align:center;
      }

      .left-part {
        background: # 999999;color:black; } </style> </head> <body> <h1"left-part">normal resize events<br></div>
<div class="right-part">Debounced resize events<br></div>
</body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js'></script>
<script>
  $(document).ready(function(){
    var win = $(window);
    var left_part = $('.left-part');
    var right_part = $('.right-part');

    function print_info(div) {
      div.append(win.width() + ' x ' + win.height() +  '<br>');
    }

    $(window).on('resize'.function(){
      print_info(left_part);
    });

    $(window).on('resize', _.debounce(function() {
      print_info(right_part);
    }, 400));
  });
</script>
</html>

Copy the code

Having said that, event throttling and event stabilization are really useful if you can’t remember them, you can also think of them metaphorically:

Event throttling is like a shuttle bus: it is fixed after a period of time and does not wait for passengers (events) to arrive at the point of departure

Event security is like a black car: it says to leave in 5 minutes, but if someone else gets on (triggers the event again within 5 minutes), you have to wait another 5 minutes before starting again (retiming)

Inappropriate 🌰 ha, help memory

Without my permission, shall not be reproduced, the article omissions superficial place, please be corrected