Search code examples
javascriptnode.jsecmascript-6v8

Why do JS modules load differently (async & sync) in a browser vs a server?


I recently read this: "ECMAScript 6 modules must work independently of whether the engine loads modules synchronously (e.g. on servers) or asynchronously (e.g. in browsers)."

Why would JS load asynchronously and synchronously, in a server vs a browser, respectively? Is this intentional?


Solution

  • Servers prefer to import modules synchronously because they are loaded quickly from the file system. In general, synchronous code is easier to write and read. It's great in Node to be able to do:

    var myModule = require("mymodule"),
        foo = require("foo");
    myModule.doThing(foo);
    

    instead of

    require("mymodule", function(err, myModule) {
        require("foo", function(err, foo) {
            myModule.doThing(foo);
        });
    });
    

    Conversely, asynchronous code is often preferable in a browser, because a network load can take a longer time and synchronous execution blocks the UI. It's preferable to keep the browser's thread free to respond to the user (and display loading animations, etc.) while quietly loading modules in the background and asynchronously responding to their completion.