-
Notifications
You must be signed in to change notification settings - Fork 210
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AMD加载器分析与实现 #17
Comments
好,上面大概聊完了模块化的背景,顺便安利了_模块化七日谈_(写的真的很好),下面步入正题:怎么实现一个AMD Loader? 读读Amd的规范,结合我们使用 当然在这之前,我们先设定一下目标,或者说手撸一个_Amd loader_的背景。 理解_Amd loader_的原理,让新手去除对 在写这篇文章的过程中,我阅读了一些相关文章,看了 1. 准备工作首先把一些工具函数,一些前置工作先拎出来讲。 1.1 怎么加载模块/文件?通过script标签。这是最简单自然的方法,其它可以ajax加载源代码eval,利用worker等等。 /**
* load script
* @param {String} url script path
* @param {Function} callback function called after loaded
*/
function loadScript(url, callback) {
var node = document.createElement('script');
var supportOnload = 'onload' in node;
node.charset = CONFIG.charset || 'utf-8';
node.setAttribute('data-module', url);
// bind events
if (supportOnload) {
node.onload = function() {
onload();
};
node.onerror = function() {
onload(true);
};
} else {
// https://github.com/requirejs/requirejs/blob/master/require.js#L1925-L1935
node.onreadystatechange = function() {
if (/loaded|complete/.test(node.readyState)) {
onload();
}
}
}
node.async = true;
node.src = url;
// For some cache cases in IE 6-8, the script executes before the end
// of the appendChild execution, so to tie an anonymous define
// call to the module name (which is stored on the node), hold on
// to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
// ref: #185 & http://dev.jquery.com/ticket/2709
baseElement ? head.insertBefore(node, baseElement) : head.appendChild(node);
currentlyAddingScript = null;
function onload(error) {
// ensure only execute once
node.onload = node.onerror = node.onreadystatechange = null;
// remove node
head.removeChild(node);
node = null;
callback(error);
}
} 代码没什么复杂逻辑,很好理解,就是创建 稍微需要注意的是这里设置了 1.2. module id的命名规则,id和url的转换规则
|
3. 最终实现https://github.com/creeperyang/amd-loader/blob/master/amd.js 有比较完整的注释,结合上面所讲的,应该比较容易理解。 |
什么是AMD(不是做显卡的:joy:)?如果不熟的话,
require.js
总应该比较熟。AMD是_Asynchronous Module Definition_的缩写,字面上即异步模块定义。
require.js
是模块加载器,实现了AMD的规范。本文想说的就是怎么实现一个类似
require.js
的加载器。但在这之前,我们应该了解下JS模块化的历史。https://github.com/Huxpro/js-module-7day
这个Slides讲的比我好的多,所以想了解前端模块化的前世今生的可以去看看。这里简单总结下:
为什么需要模块化?
前端模块历史?
但模块化还需要解决加载问题:
define
包裹,在打包时解决模块化;The text was updated successfully, but these errors were encountered: