An extremely simple implementation method of requirejs, and implementation of requirejs
The source code analysis of require and sea has been written in my previous blog. Today I want to share a very simple core code (about 60 lines without comments or blank lines ), no fault tolerance judgment.
Require. js
The require function is implemented in one sentence:
Load the require module in sequence, monitor the onload event of the script, judge that all modules are loaded successfully, and execute the require callback. If only one parameter is included and not an array, it means the return module is loaded successfully.
// Mark the number of successfully loaded rows var REQ_TOTAL = 0; // The module exports the window. exports ={}; // record the order of each module var exp_arr = []; // determine whether the Array function isArray (param) {return param instanceof Array ;} // require implements function require (arr, callback) {var req_list; if (isArray (arr) {req_list = arr;} else {req_list = [arr];} var req_len = req_list.length; // The module loads for (var I = 0; I <req_len; I ++) {var req_item = req_list [I]; var $ script = createScript (req_item, I); var $ node = document. querySelector ('head'); (function ($ script) {// checks the onload event $ script of the script. onload = function () {REQ_TOTAL ++; var script_index = $ script. getAttribute ('index'); exp_arr [script_index] = exports; window. exports = {}; // after all links are loaded successfully, run callback if (REQ_TOTAL = req_len) {callback & callback. apply (exports, exp_arr) ;}}$ node. appendChild ($ script) ;}) ($ script) ;}// create a script tag function createScript (src, index) {var $ script = document. createElement ('script'); $ script. setAttribute ('src', src); $ script. setAttribute ('index', index); return $ script ;}
Then I wrote two js files for the export module and wrote only the simplest exports implementation.
Define. js
exports.define = { topic: 'my export', desc: 'this is other way to define ', sayHello: function() { console.log('topic ' + this.topic + this.desc); }}
Define2.js
exports.define = { name: 'xm', age: 22, info: function() { console.log('topic ' + this.name + this.age); }}
Then it's easy to test the demo.
// Test demo require (['.. /res/define. js ','.. /res/define2.js '], function (def, def2) {def. define. sayHello (); def2.define.info ();});
The above is an extremely simple requirejs implementation method provided by Alibaba Cloud ~