使用requirejs在onload之前加载javascript文件 [英] load javascript file before onload with requirejs

查看:336
本文介绍了使用requirejs在onload之前加载javascript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用requireJS。但是,我有一个需要在DOM之前加载的lib。但是,这不是requireJS所发生的事情

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>

使用app.js

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

例如,如果我只是直接在头部加载这个脚本(没有requireJS)就行了。它是否有一个require-config-option,所以我可以立即加载一个特定的文件(同步?)?

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?) ?

推荐答案

Requirejs因其异步电源而闻名。但是当你需要某种类型的订单来加载文件时由于依赖关系,在require.config中有一个 shim config:

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:为不使用的较旧的传统浏览器全局脚本配置依赖项,导出和自定义初始化define()声明依赖项并设置模块值。

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.

所以假设你有一个依赖于Underscore和jQuery的骨干应用程序,并且您希望它们加载按此顺序然后你会:

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){
  //.....
});

因此,RequireJS允许我们使用 shim 配置来定义序列需要按正确顺序加载的文件。

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

这篇关于使用requirejs在onload之前加载javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆