Have require.js load my files only when I actually need them

被刻印的时光 ゝ 提交于 2019-12-11 10:40:33

问题


I know this is the whole point of require.js, but it does not behave this way in my situation.

I am creating a single page Backbone.js application. The main entry point to the application is trough a router. Let's say I have 3 routes:

users: function(){
    require('users');
},
products: function(){
    require('products');
},
groups: function(){
    require('groups');
},

Based on the function I call I want to load the file, but require.js does not do this.

Instead it downloads all the files for my complete website everywhere there is a require. I haven't even called the function but it loads the file.

Is there a way to have require.js behave as it should, and download the file only when I am actually inside the function.


回答1:


You can basically do what you have in your code snippet. It'd look something like this:

users: function(){
    require(['users'], function(Users){
        //Code
    });
},
products: function(){
    require(['products'], function(Products){
        //Code
    });
},
groups: function(){
    require(['groups'], function(Groups){
        //Code
    });
},


来源:https://stackoverflow.com/questions/10474479/have-require-js-load-my-files-only-when-i-actually-need-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!