许多人都知道,Google提供了一个API,您可以通过调用一个简单的函数来加载特定的模块/库:
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.7.1");
google.load("jqueryui", "1.8.2");
</script>
我目前正在开发自己的代码库,我想在我的网站中轻松有效地分发代码库,我想不出比上面更好的方法。
但是,我不太清楚为此编写代码的最佳方法是什么。显然我的图书馆将是一个对象,所以将从这样的事情开始(我认为,如果我错了,请纠正我):
function company(){
this.load = function(modules){
// Modules is an array of modules to load
// Load the separate modules here
// from external files in their minified format
}
}
var company = new company;
company.load(['forms']);
上述方法是正确的方法吗?然后,我如何从单独的文件中加载模块?
答案 0 :(得分:0)
您可以使用CommonJS Module规范。然后,您可以使用RequireJS加载它们。
答案 1 :(得分:0)
在寻找并获得其他人的经验后,我认为以下是最好的方法。 其他人可能不同意,随意发表评论
/**
* Sine Macula Javascript API
* The Sine Macula API contains all base functions for use throughout
* all websites
* @name class.sinemacula.js
* @author Ben Carey
* @version 1.0
* @date 25/10/2012
* @copyright (c) 2012 Sine Macula Limited (sinemaculammviii.com)
*/
function SineMacula(){
// Only proceed if jQuery has been loaded
if(typeof jQuery=='undefined'){
// jQuery has not been loaded
console.log('jQuery has not been loaded');
}else{
/**
* Sine Macula Load
* Load the Sine Macula Libraries and Plugins
* into the current document
*
* The options:
* - package: the package of libraries to load
* - packageURL: a remote source to load the package details from
* - libraries: any additional libraries to load
*
* @param object options The options for the Sine Macula load
*/
this.load = function(options){
var url,query,script;
// Set the defaults for the loader
var options = $.extend({
package: 'none', // Do not load any packages by default
packageURL: false, // Do not retrieve the package details from a URL by default
libraries: [] // Do not load any libraries by default
},options);
// Build the query based on the parameters supplied
if(options.packageURL){
// Build the query to allow for a remote
// package definition
query = '?packageURL='+encodeURIComponent(options.packageURL);
}else if(options.package=='none'){
query = '?libraries='+encodeURIComponent(options.libraries.join());
}else{
query = encodeURIComponent(options.package)+'/?libraries='+encodeURIComponent(options.libraries.join());
}
// Complete the url by appending the query
url = '//libraries.sinemaculammviii.com/'+query;
// Append the script tag to the end of the document
script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
$('head')[0].appendChild(script);
}
}
};