一個極為簡單的requirejs實現

來源:互聯網
上載者:User

標籤:

require和 sea的源碼分析,我之前的部落格有寫過, 今天我想分享的是一個很簡單的核心代碼(不帶注釋和空行大概60行), 沒有容錯判斷。

require.js

require函數實現用一句話概括:

依次載入require的模組,然後監測script的onload事件,判斷所有模組載入成功,執行require的callback, 如果只帶一個參數且不是數組,就是載入成功後return 模組。

 1 //標記已經載入成功的個數 2 var REQ_TOTAL = 0; 3 //模組匯出 4 window.exports = {}; 5 //記錄各個模組的順序 6 var exp_arr = []; 7  8 //判斷是否數組 9 function isArray(param) {10     return param instanceof Array;11 }12 13 //require 真正實現14 function require(arr, callback) {15 16     var req_list;17 18     if(isArray(arr)) {19         req_list = arr;20     } else {21         req_list = [arr];22     }23     var req_len = req_list.length;24 25     //模組逐個載入26     for(var i=0;i<req_len;i++) {27         var req_item = req_list[i];28 29         var $script = createScript(req_item, i);30 31         var $node = document.querySelector(‘head‘);32 33         (function($script) {34             //檢測script 的onload事件35             $script.onload = function() {36                 REQ_TOTAL++;37 38                 var script_index = $script.getAttribute(‘index‘);39 40                 exp_arr[script_index] = exports;41 42                 window.exports = {};43 44                 //所有連結載入成功後,執行callback45                 if(REQ_TOTAL == req_len) {46                     callback && callback.apply(exports, exp_arr);47 48              
49 }50 51 }52 53 $node.appendChild($script);54 })($script);55 56 }57 58 }59 60 //建立一個script標籤61 function createScript(src, index) {62 var $script = document.createElement(‘script‘);63 64 $script.setAttribute(‘src‘, src);65 $script.setAttribute(‘index‘, index);66 67 return $script;68 }

 

然後寫了2個匯出模組的js檔案, 唯寫了最簡單的exports實現

define.js

1 exports.define = {2     topic: ‘my export‘,3     desc: ‘this is other way to define ‘,4     sayHello: function() {5         console.log(‘topic ‘ + this.topic + this.desc);6     }7 }

define2.js

1 exports.define = {2     name: ‘xm‘,3     age: 22,4     info: function() {5         console.log(‘topic ‘ + this.name + this.age);6     }7 }

 

然後測試demo很簡單

1 //測試demo2 require([‘../res/define.js‘, ‘../res/define2.js‘], function(def, def2) {3     def.define.sayHello();4 5     def2.define.info();6 });

 

demo地址 :https://skyweaver213.github.io/requirejs-demo/example/dev/demo.html

github地址:https://github.com/skyweaver213/requirejs-demo

 

一個極為簡單的requirejs實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.