RequireJS加载js文件

来源:互联网 发布:知乎 玄幻小说推荐 编辑:程序博客网 时间:2024/05/17 01:54

RequireJS的目标是鼓励代码的模块化,它使用了不同于传统

//This sets the baseUrl to the "scripts" directory, and loads a script that will have a module ID of 'main'<script data-main="scripts/main.js" src="scripts/require.js"></script>

baseUrl亦可通过RequireJS config手动设置。如果没有显示指定config及data-main,则默认的baseUrl为包含RequireJS的那个HTML页面的所属目录。
RequireJS默认嘉定所有的依赖资源都是js脚本,因此无需再module ID上再加”.js”后缀,RequireJS在进行moduleID到path的解析时会自动不上后缀。你可以通过paths config设置一组脚本,这些有助于我们在使用脚本时码更少的字。
有时候你想避开“baseUrl+paths”的解析过程,而是直接指定加载某一个目录下的脚本。此时可以这样做:如果一个module ID符合下述规则之一,其ID解析会避开常规的“baseUrl+paths”配置,而是直接将其加载为一个相对于当前HTML文档的脚本:

  • 以“.js”结束。
  • 以“/”开始。
  • 包含URL协议,如“http:”or“https:”。
    一般来说,最好还是使用baseUrl及“paths”去设置moduleID。它会给你带来额外的灵活性,如便于脚本的重命名、重定位等。同时,为了避免凌乱的配置,最好不要使用多级嵌套的目录层次来组织代码,而是要么将所有的脚本都放置到baseUrl中个,要么分置为项目库/第三方库的一个扁平结构。

  • www/

    • index.html
    • js/
      • app/
        • sub.js
      • lib/
        • jquery.js
        • canvas.js
      • app.js

    index.html

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

app.js

requirejs.config({  //By default load any module IDs from js/lib  baseUrl: 'js/lib',  //except, if the module ID starts with "app",  //load it from js/app directory. paths  //config is relative to the baseUrl, and   //never includes a ".js" extension since  //the paths config could be for a directory  paths: {    app: '../app'  }});//Start the main app logic.requirejs(['jquery', 'canvas', 'app/sub'], function($, canvas, sub){  //jQuery, canvas and the app/sub module are all  //loaded and can be userd here now.}

理想情况下,每个加载的脚本都是通过define()来定义的一个模块;但有些“浏览器全局变量注入”型的传统/遗留库并没有使用define()来定义他们的依赖关系,你必须为此使用shim config来指明它们的依赖关系。如果你没有指明依赖关系,加载可能报错。这是因为基于速度的原因,RequireJS会异步地以无序的形式加载这些库。

注意
1、data-main指定的js文件也会被当做一个module,命名为其js文件名称。
2、在require config中paths不仅可以配置一个js文件的module ID,还可以配置一个文件夹的module ID,那么这个文件夹下所有的js文件都可以用这个文件夹的moduleID/js文件名表示。