How to inject a dependency on an external script

时间:2015-06-25 18:52:39

标签: javascript dependency-injection requirejs

I'm using a cloud service called Parse in a JavaScript closure injected with require.js: define([/*some dependencies*/], function(/*some dependencies*/) { ... // using Parse. For example: var TestObject = Parse.Object.extend("TestObject"); ... } The tutorial for using Parse in Javascript instructs to include their script in the HTML header: <script src="//www.parsecdn.com/js/parse-1.4.2.min.js"></script> I don't want the HTML page to depend on Parse and I don't want to clutter the HTML with external scripts. Instead, I would like to require parse-1.4.2.min.js directly from the script. What's the proper way of doing so? How do I define this dependency and make it work?

2 个答案:

答案 0 :(得分:0)

与jQuery类似,Parse将其自身添加到负载的全局范围。如果没有其他脚本依赖它,它可以简单地作为依赖项包含在模块中或需要调用。

require([
    'https://www.parsecdn.com/js/parse-1.4.2.min.js',
], function () {
    console.log(Parse);
}

如果您正在使用依赖于Parse(或任何其他库)的任何其他非AMD脚本,则需要使用config / shim。它告诉requireJS它应该根据它们的依赖性加载脚本的顺序。

E.g。当使用jQuery插件时,你不希望它在jQuery本身之前加载和执行。

配置/路径设置还可以通过允许在单个位置定义脚本位置然后通过引用包含来帮助组织项目。

有关详细信息,请参阅requireJS docs

以下配置/需要成功加载Parse和虚构插件:

require.config({

  // define paths to be loaded, allows locations to be maintained in one place
  paths: {
    parse: 'https://www.parsecdn.com/js/parse-1.4.2.min',
    plugin: 'example-non-amd-parse-plugin.js'
  },

  // define any non-amd libraries and their dependancies
  shim: {
    parse: {
      exports: 'Parse'
    },
    plugin: {
      exports: 'plugin',
      deps: ['parse']
    }
  }
});

require(['parse'], function(Parse){
  console.log(Parse);
});

// note Parse is not required
require(['plugin'], function(plugin){

  // Parse is available as it is depended on by plugin and on the global scope
  console.log(Parse, plugin);
});

答案 1 :(得分:-4)

所以我毕竟只是写了这个,它似乎工作。首先不知道问题是什么......

define(["https://www.parsecdn.com/js/parse-1.4.2.min.js"], 
   function () {