load javascript file before onload with requirejs

时光总嘲笑我的痴心妄想 提交于 2019-12-08 07:51:25

问题


I would like to use requireJS. However, I have a lib that needs to be loaded before the DOM. However, this is not what happens with requireJS

<html>
    <head>
        <script data-main="/app" src="/require.js"></script>
    </head>

    <body>
        <bar-foo/>
    </body>
</html>

With app.js

require.config({
    paths: {
        'customElement': '/customElement',
        'barfoo': '/barfoo'
    },
    shim: {
        barfoo: {
            deps: [ 'customElement' ]
        }
    }
});
define(['barfoo'], function() {
    ....
}

For example, if I simply load this script directly in the head (without requireJS) it works fine. Is there a require-config-option so I can load a specific file immediately (synchronously?) ?


回答1:


Requirejs is known for it's asynchronous power. However when you need some sort of an order in which you want files to be loaded due to dependencies, in require.config there is a shim config:

shim: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.

So let's say you have a backbone app that depends on Underscore and jQuery, and you want them to load in that order then your would:

require.config({
paths: {
    'Backbone': '/Backbone',
    'Underscore': '/Underscore',
    'jQuery': '/jQuery'
},
shim: {
    'Backbone': [ 'Underscore', 'jQuery' ]
}
});

require(['Backbone'], function(Backbone){
  //.....
});

So, RequireJS allows us to use the shim config to define the sequence of files which need to be loaded in correct order.



来源:https://stackoverflow.com/questions/21188571/load-javascript-file-before-onload-with-requirejs

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