SoFunction
Updated on 2025-02-28

An extremely simple method to implement requirejs

Source code analysis of require and sea. I have written about the previous blog. Today I want to share a very simple core code (about 60 lines without comments and blank lines), without fault tolerance.

The implementation of the require function is summarized in one sentence:

Load the required modules in turn, then monitor the script's onload event, judge that all modules are loaded successfully, and execute the require callback. If you only bring one parameter and are not an array, you will return the module after it is loaded successfully.

 

//The number of tags that have been loaded successfullyvar REQ_TOTAL = 0;
//Module Export = {};
//Record the order of each modulevar exp_arr = [];

//Judge whether it is an arrayfunction isArray(param) {
  return param instanceof Array;
}

//requirefunction require(arr, callback) {

  var req_list;

  if(isArray(arr)) {
    req_list = arr;
  } else {
    req_list = [arr];
  }
  var req_len = req_list.length;

  //Modules load one by one  for(var i=0;i<req_len;i++) {
    var req_item = req_list[i];

    var $script = createScript(req_item, i);

    var $node = ('head');

    (function($script) {
      //Detection of script onload event      $ = function() {
        REQ_TOTAL++;

        var script_index = $('index');

        exp_arr[script_index] = exports;

         = {};

        // After all links are loaded successfully, execute callback        if(REQ_TOTAL == req_len) {
          callback && (exports, exp_arr);

       
        }

      }

      $($script);
    })($script);

  }

}

//Create a script tagfunction createScript(src, index) {
  var $script = ('script');

  $('src', src);
  $('index', index);

  return $script;
}

Then I wrote 2 js files for export modules, and only the simplest exports implementation

 = {
  topic: 'my export',
  desc: 'this is other way to define ',
  sayHello: function() {
    ('topic ' +  + );
  }
}

 = {
  name: 'xm',
  age: 22,
  info: function() {
    ('topic ' +  + );
  }
}

Then it's easy to test the demo

//Test demo require(['../res/', '../res/'], function(def, def2) {
   ();
 
   ();
 });

The above is the entire content of an extremely simple requirejs implementation method brought to you. I hope everyone supports me~