Proxy mode of JavaScript design pattern-lazy loading of large files

Before reading this article, it is recommended to look at the proxy mode of the previous JavaScript design pattern-realize loading image loading

1. Demand

Suppose there is a very large js file, we only trigger to load it when we need it. For example, there is a console that is used to print logs on the mobile terminal. After pressing F2, the file is loaded and the related logs are printed. The effect is as follows:

2. Realize

  • First we create the index.html file, the html code is as follows:

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>虚拟代理惰性加载文件</title>
        <style>
            #consoleContent{
                border:1px solid #ccc;
                width: 200px;
                height: 300px;
                color:#333;
                overflow: auto;
                display: none;
            }
            #consoleContent p{
                margin: 0;
                padding: 5px 10px;
                vertical-align: middle;
                border-bottom:1px solid #ccc;
                overflow-wrap: break-word;
            }
        </style>
    </head>
    
    <body>
        <section id="consoleContent"></section>
    </body>
    
    </html>
  • Then insert the script script in the above file, the code is as follows:

    let miniConsole = (function () {
            let cache = [];
            // 当用户按下F2时,开始加载真正的miniConsole.js 
            const handler = function (ev) {
                if (ev.keyCode === 113) {
                    const script = document.createElement('script');
                    script.onload = function () {
                        for (let i = 0, fn; fn = cache[i++];) {
                            fn();
                        }
                        cache = null;
                    };
                    script.type = 'text/javascript';
                    script.src = "miniConsole.js";
                    document.getElementsByTagName('head')[0].appendChild(script);
                    document.removeEventListener('keydown', handler);
                }
            };
            document.addEventListener('keydown', handler, false);
            return {
                log: function () {
                    const args = arguments;
                    cache.push(function () {
                        // 不直接用miniConsole.log(args)是为了解决传多个参数的问题
                        return miniConsole.log.apply(miniConsole,args);
                    })
                }
            }
        })();
        miniConsole.log(11,22);
        miniConsole.log(22);
        miniConsole.log(33);

Since the object in the js file we want to load is miniConsole, a proxy object with the same name is created:

  1. Add monitoring key events in it, when the user presses F2, the real miniConsole.js file will be loaded;
  2. Implement the log method corresponding to the ontology. When the file is not loaded, it is first stored in the cache object cache;
  3. After the real miniConsole.js is loaded, call the cached method in the cache to realize the real printing function.
  • Finally, the main code of miniConsole.js is roughly as follows:

    miniConsole = {
        log: function () {
            const p = document.createElement('p');
            p.innerHTML = Array.prototype.join.call(arguments);
            const content = document.getElementById('consoleContent');
            content.appendChild(p);
            content.style.display = 'block';
        }
    };

3. Summary of ideas

The above miniConsole.js sometimes needs to handle various types of log printing, resulting in larger files. But our function is not always used by users, so we implement lazy loading to reduce network overhead.

When we encounter large files and unnecessary functions, we can use virtual agents to implement lazy loading. The steps are as follows:

  1. Create a proxy object with the same name as the original file interface;
  2. Load the original file when you need it in a specific situation (such as monitoring key presses);
  3. Cache all calls in the proxy object interface, monitor file loading, and execute it when the file is loaded.

Agency model series:

Realize loading image loading

Performance optimization for frequent requests

Note: Refer to the book "JavaScript Design Patterns and Development Practice", if you like, you can follow the blogger, and keep updating the design pattern series study notes~

Don't be stingy with likes and comments~

 

Guess you like

Origin blog.csdn.net/qq_39287602/article/details/108751853