Why do concatenated RequireJS AMD modules need a loader?

前端 未结 5 1423
后悔当初
后悔当初 2021-01-30 17:05

We love RequireJS and AMD during development, where we can edit a module, hit reload in our browser, and immediately see the result. But when it comes time to concatenate our mo

5条回答
  •  礼貌的吻别
    2021-01-30 17:26

    An AMD optimiser has the scope to optimise more than the number of files to be downloaded, it can also optimise the number of modules loaded in memory.

    For example, if you have 10 modules and can optimise them to 1 file, then you have saved yourself 9 downloads.

    If Page1 uses all 10 modules then that's great. But what if Page2 only uses 1? An AMD loader can delay the execution of the 'factory function' until a module is require'd. Therefore, Page2 only triggers a single 'factory function' to execute.

    If each module consumes 100kb of memory upon being require'd, then an AMD framework that has runtime optimisation will also save us 900kb of memory on Page2.

    An example of this could be an 'About Box' style dialog. Where the very execution of it is delayed until the very last second as it won't be accessed in 99% of cases. E.g. (in loose jQuery syntax):

    aboutBoxBtn.click(function () {
        require(['aboutBox'], function (aboutBox) {
            aboutBox.show();
        }
    });
    

    You save the expense of creating the JS objects and DOM associated with the 'About Box' until you are sure it's necessary.

    For more info, see Delay executing defines until first require for requirejs's take on this.

提交回复
热议问题