Synchronous and Asynchronous Loading of JavaScript Files

Keywords: Javascript Webpack IE github

References to JS files are handled well by many frameworks and tools (such as webpack, commonjs, requiresjs, etc.). Despite these frameworks, it is helpful to understand the native loading method. This paper briefly describes the synchronous and asynchronous loading methods of some JS files.

Synchronous loading

It can be inserted in html file with < script > tag, which is the most basic way to start school.

Prepare two js files as follows:
calc1.js

console.log('calc1 loading begin')

function add(...args) {
    return args.reduce((currentTotal, i) => currentTotal + i, 0);
}

console.log('calc1 loading end')

calc2.js

console.log('calc2 loading begin')

console.log(add(1,2,3))

console.log('calc2 loading end')

Cal2.js is dependent on calc1.js.

The html file is as follows:

<body>

    <script src="calc1.js">
    </script>
    
    <script src="calc2.js">
    </script>
</body>

In this way, file loading is synchronous. That is to say, calc1.js is loaded only after the completion of loading, so it ensures that calc2.js can always correctly call the add function in calc1. The debugging results in Chrome are as follows:

However, the disadvantage of synchronous loading is obvious. If there are multiple files, the whole loading time will be very long, and the user interface response will be blocked.

Asynchronous loading through Script Element

The advantage of asynchronous loading is that it can load multiple js files at the same time, and because it is asynchronous, it will not block the user interface and has a good user experience. Of course, the disadvantage is that the loading order of dependent files cannot be guaranteed.

html code

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        var script1 = document.createElement('script');
        script1.src='calc1.js';
        script1.type='text/javascript';

        var script2 = document.createElement('script');
        script2.src='calc2.js';
        script2.type='text/javascript';

        document.getElementsByTagName('head')[0].appendChild(script1).appendChild(script2);
    </script>
</head>

Debugging results in Chrome sometimes output correctly as follows:

But sometimes, because clac1.js is not loaded first, calc2.js will report an error when it is executed.

So we need to solve the problem of loading order to ensure that calc1.js loads first.

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function loadScript(file, callbackFn) {
            var script = document.createElement('script');
            script.src= file;
            script.type='text/javascript';
            // Listen for onload time, after the current js file is loaded, load the next
            script.onload = callbackFn;
            document.getElementsByTagName('head')[0].appendChild(script)
        }
        
        loadScript('calc1.js', function () {
            loadScript('calc2.js');
        } );

    </script>
</head>

That way you can always output the right results.

Loading JS files through AJAX

  <script>
        function loadScript(file, callbackFn) {
            var xhr = new XMLHttpRequest();
            xhr.open('get', file, true);
            // for IE
            if (xhr.onreadystatechange) {
                xhr.onreadystatechange = function () {
                    console.log(xhr.readyState, xhr.status);
                    if (xhr.readyState == 4) {
                        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                            insertScriptText(xhr.responseText);
                            if (callbackFn) {
                                callbackFn();
                            }
                        }
                    }
                }
            } else {
                xhr.onload = function () {
                    insertScriptText(xhr.responseText);
                    if (callbackFn) {
                        callbackFn();
                    }
                }
            }
            xhr.send(null);
        }

        function insertScriptText(scriptText) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.text = scriptText;
            document.body.appendChild(script);
        }

        loadScript('calc1.js', function () {
            loadScript('calc2.js');
        });

    </script>

It can also output the results correctly.

summary

If it is a single or a few js files, you can insert script tags at the end of html body and load them synchronously. Webpack is actually a combination of multiple js files into one, and then inserts script references into the body.

If there are multiple js files, asynchronous loading is recommended to avoid blocking interface rendering and shorten the overall loading time. In this paper, script element and Ajax are introduced, and some examples are given to illustrate the loading order of dependent files. Please refer to https://github.com/JackieGe/J...

Posted by tomato on Sun, 02 Jun 2019 13:38:05 -0700