zoukankan      html  css  js  c++  java
  • 模块加载系统

    模块加载系统初尝版,2个暴露函数:
    加载模块:require(requireLists,callback);
    require(['core','dom/selector'],function(){
      //coding here,
      //callbacks
    })
    定义模块:define(id,requireLists,callback);
    define('id',['core','dom/selector'],function(){
      //coding here
      //callbacks
    })

    View Code
     1 (function(win) {
    2 loadedModules = {};
    3 var reg_module_name = /(?:^|\/)([^(\/]+)$/;
    4 function require(modules, callback) {
    5 var moduleNames = [],
    6 self = arguments.callee;
    7 for (var i = 0, l = modules.length; i < l; i++) {
    8 var matt = modules[i].match(reg_module_name);
    9 moduleNames.push(matt[1]);
    10 if (! (matt[1] in loadedModules) && ! detectExist(modules[i])) {
    11 appendScript(modules[i]);
    12 }
    13 }
    14 detectLoads(moduleNames, callback);
    15 }
    16 function define(id, requireModules, callback) {
    17 require(requireModules, function() {
    18 callback();
    19 loadedModules[id] = 1;
    20 })
    21 }
    22 function detectExist(module) {
    23 var exist = false,
    24 scripts = document.getElementsByTagName("script");
    25 for (var i = 0, l = scripts.length; i < l; i++) {
    26 if (scripts[i].getAttribute("src") === module + ".js") {
    27 exist = true;
    28 break;
    29 }
    30 }
    31 return exist;
    32 }
    33 function appendScript(module) {
    34 var script = document.createElement("script");
    35 script.setAttribute("charset", "utf-8");
    36 script.setAttribute("defer", true);
    37 script.setAttribute("src", module + ".js");
    38 document.getElementsByTagName("head")[0].appendChild(script);
    39 }
    40 function detectLoads(modules, callback) {
    41 var flag = true,
    42 args = arguments,
    43 fn = args.callee;
    44 for (var i = 0, l = modules.length, el; i < l; i++) {
    45 el = modules[i];
    46 if (!loadedModules[el]) {
    47 flag = false;
    48 break;
    49 }
    50 }
    51 if (flag) {
    52 callback();
    53 } else {
    54 setTimeout(function() {
    55 fn.apply(null, args);
    56 });
    57 }
    58 }
    59 win.require = require;
    60 win.define = define;
    61 })(this);




  • 相关阅读:
    MySQL数据类型2
    MySQL数据类型1
    powerdesigner使用之——从“概念模型”到“物理模型”
    javascript中click和onclick的区别
    eclipse将javaSE项目导出成可执行jar包
    配置SQLServer,允许远程连接
    VirtualBox虚拟机中安装XP系统
    fastjson 的使用总结
    idea前端页面不刷新----springboot
    后台可以用layui快速开发
  • 原文地址:https://www.cnblogs.com/jiajiaobj/p/2339316.html
Copyright © 2011-2022 走看看