简体   繁体   English

requireJS模块加载

[英]requireJS module loading

I need some help with the concept of only loading modules when they are needed using requireJS 我需要一些帮助,只需要在需要时使用requireJS加载模块

this is my main.js 这是我的main.js

require(['jquery', 'path/somemodule'],
function($, somemodule) {
$(document).ready(function() {
    somemodule.init()
})

})

and in the somemodule.js 并在somemodule.js

 define(['jquery', 'path/someothermodule'], function ($, someothermodule) {
 "use strict";
var somemodule;

somemodule = {
init: function () {
    someothermodule.init()
}
}
return somemodule;
)}

right now somemodule.js and someothermodule.js is loaded on all pages. 现在somemodule.js和someothermodule.js被加载到所有页面上。 How do I only load it when it's needed? 如何在需要时才加载它?

When you require a module2 from module1 using the standard define() syntax module1 will not load/run until module2 has been fully loaded. 当您需要module1中的module2使用标准的define()语法时,module1将无法加载/运行,直到module2完全加载。 That looks like this: 看起来像这样:

// inside module1
define(['module2'], function(mod2) {
   // we don't get here until AFTER module2 has already been loaded
});

An alternative to lazy-load module2 looks like this: lazy-load module2的替代方案如下所示:

// inside module1
define([], function() {
   require(['module2'], function(mod2) {
       // we don't get here until AFTER module2 has already been loaded
   });
   // but we DO get here without having loaded module2
});

Now you have to program somewhat carefully to make sure you don't run into any issues with asynchronicity. 现在你必须仔细编程,以确保不会遇到任何异步问题。

In your case you can modify your main.js file 在您的情况下,您可以修改main.js文件

require(['jquery'],
function($) {
    // jquery is loaded, but somemodule has not

    if(thisPageNeedsSomeModule) {
        require(['path/somemodule'],
        function(somemodule) {
            // now somemodule has loaded
            $(document).ready(function() {
                somemodule.init()
            })
        });
    }
})

Your main.js file will load any file paths provided to it, so long as other elements of your application specify them as dependencies. 您的main.js文件将加载提供给它的任何文件路径,只要应用程序的其他元素将它们指定为依赖项。 See my example main.js file: 看我的示例main.js文件:

require.config({

    paths: {
        'app': 'app',
        'underscore':'bower_components/underscore/underscore-min',
        'backbone':'bower_components/backbone/backbone-min',
        'marionette':'bower_components/backbone.marionette/lib/backbone.marionette.min',
        'jquery': 'bower_components/jquery/jquery.min',
        'tpl':'bower_components/requirejs-tpl/tpl',
        'bootstrap':'bower_components/bootstrap/dist/js/bootstrap.min',
        'leaflet':'bower_components/leaflet/leaflet',
        'leaflet.markercluster':'bower_components/leaflet/leaflet.markercluster',
    },
    shim: {
        'underscore': {
            exports: '_'
        }, 
        'leaflet': {
            exports: 'L'
        }, 
        'leaflet.markercluster': {
            deps: ['leaflet']
        },
        'backbone': {
            deps: ['underscore']
        },
        'marionette': {
            deps: ['backbone']
        },
        'jquery': {
            exports: '$'
        },  
        'bootstrap': {
            deps: ['jquery']
        },
        'app': {
            deps: ['jquery', 'leaflet','bootstrap', 'leaflet.markercluster', 'marionette', 'tpl']
        },
        'app.elem': {
            deps:['app']
        },
        'app.api': {
            deps:['app']
        }
    }
})

require(['app','app.api','app.elem'], function() {
    App.start();
})

And my initial application file: 我的初始申请文件:

define(['router', 'collections/moments'], function(router, momentCollection) {

    // Boot the app!

    App = new Marionette.Application();

    App.LocResolve = false; // Have we resolved the user's location?
    App.Locating = true; // Are we actively tracking the user's location?

    App.FileReader = window.FileReader ? new FileReader : null;

    App.Position = null; // Instant access to Lat & Lng of user.

    App.MomentsRaw = null; // Keep cached copy of returned data for comparison.

    App.Moments = new momentCollection; // Current collection of moments.
    App.Markers = new L.MarkerClusterGroup(); // Create Marker Cluster Group

    App.View = null; // Current view.

    // Marionette Regions

    App.addRegions({
        header: '#header',
        map: '#map',
        list: '#list',
        modal: '#modal',
    });

    return App
})

I noticed that you aren't passing in a configuration object - is this intentional? 我注意到你没有传入配置对象 - 这是故意的吗? If you use R.js, the build optimizer, it will automatically remove unused vendor files for you. 如果您使用构建优化器R.js,它将自动删除未使用的供应商文件。

In short, sets paths to your vendor files in the require.js config, then call upon them via define() whenever you need a particular asset. 简而言之,在require.js配置中设置供应商文件的路径,然后在需要特定资产时通过define()调用它们。 This will ensure that only files you need are used. 这将确保仅使用您需要的文件。 Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM