マイモジュールロードシステムv 9(例ダウンロード付)

15743 ワード

モジュールロードシステムは私のフレームワークのコアモジュールの一部であり、domReadyと徹底的に統合されています.もちろん、コアモジュールは、数のグループ化、タイプ判定、簡単なイベントバインドなど、他の一般的な方法も提供しています.このリリースでは、次のような改善点があります.
  • HTML 5 History APIは、新しい「URLを変更してページをリフレッシュしない」技術をもたらし、コアモジュールにダイナミックネーミングスペース(DOC.URL.replace(/(W|(#.+)/g,'))が見つからない可能性があるため、onpopstateイベントを追加してネーミングスペースを同期します.
  • モジュールをマウントするために一時的に生成されたscriptノードは、operaがreadyStateプロパティにアクセスしないようにし、iframe注入scriptで「getting readyState has failed in runtime_onload_handler handleReadyState」異常
  • を回避する.
  • domを捨てる.K、もっと大衆的なdomを使います.noopメソッド.
  • 簡単な非同期キューでdomを書き換える.readyとエラースタックdom.stackは、そのため機能が強化され、コアモジュール全体のコード量が低下しました.

  • テストに合格したブラウザ:IE 6-9 FF 3.6.12 FF5.1 opera11.50 safari 5 chrome14.0.8
    
    
    //=========================================
    
    //       (    )2011.8.20 by     
    
    //=========================================
    
    (function(global,DOC){
    
        var
    
        _dom = global.dom,
    
        w3c = DOC.dispatchEvent, //w3c    
    
        namespace = DOC.URL.replace(/(\W|(#.+))/g,''),
    
        HEAD = DOC.head || DOC.getElementsByTagName("head")[0],
    
        class2type = {
    
            "[object HTMLDocument]"   : "Document",
    
            "[object HTMLCollection]" : "NodeList",
    
            "[object StaticNodeList]" : "NodeList",
    
            "[object IXMLDOMNodeList]": "NodeList",
    
            "[object DOMWindow]"      : "Window"  ,
    
            "null"                    : "Null"    ,
    
            "NaN"                     : "NaN"     ,
    
            "undefined"               : "Undefined"
    
        },
    
        toString = class2type.toString;
    
        /**
    
         *   ,           
    
         * @param {Object} target     
    
         * @param {Object} source    
    
         * @return  {Object}     
    
         */
    
        function mix(target, source){
    
            var args = [].slice.call(arguments),key,
    
            ride = typeof args[args.length - 1] == "boolean" ? args.pop() : true;
    
            for(var i = 1;source = args[i++];){
    
                for (key in source) {
    
                    if (ride || !(key in target)) {
    
                        target[key] = source[key];
    
                    }
    
                }
    
            }
    
            return target;
    
        }
    
        /**
    
         * @class dom
    
         * dom Framework        ,
    
         *     DOC.URL.replace(/(\W|(#.+))/g,''),           
    
         *     dom,             
    
         * @namespace dom
    
         */
    
        var dom = function(expr,context){
    
            if(dom.type(expr,"Function")){ //   safari ,typeof nodeList    function,      dom.type
    
                dom.ready(expr, true);
    
            }else{
    
                if(!dom.fn)
    
                    throw "must load the 'node' module!"
    
                return new dom.fn.init(expr,context);
    
            }
    
        }
    
    
    
        mix(dom,{
    
            uuid:1,
    
            HTML:DOC.documentElement,
    
            HEAD:HEAD,
    
            rword:/[^, ]+/g,
    
            rreadystate: /loaded|complete|undefine/i,
    
            "@name":"dom",
    
            "@debug":true,
    
            "@emitter": w3c ? "addEventListener" : "attachEvent",
    
            /**
    
             *     (   jquery noConflict)
    
             * @param {String} name       
    
             */
    
            exports: function(name) {
    
                _dom && (global.dom = _dom);
    
                name = name || dom["@name"];
    
                dom["@name"] = name ;
    
                global[name] = global[namespace] = this;
    
            },
    
            /**
    
             *    
    
             * @param {ArrayLike} nodes          
    
             * @param {Number} start   。           。     ,     
    
             * @param {Number} end    。         
    
             * @return {Array}
    
             */
    
            slice: function (nodes, start, end) {
    
                for(var i = 0,n = nodes.length, result = []; i < n; i++){
    
                    result[i] = nodes[i];
    
                }
    
                if (arguments.length > 1) {
    
                    return result.slice(start , (end || result.length));
    
                } else {
    
                    return result;
    
                }
    
            },
    
            noop:function() {},
    
            /**
    
             *                  
    
             * @param {Any} obj       
    
             * @param {String} str       
    
             * @return {String|Boolean}
    
             */
    
            type : function(obj, str){
    
                var result = class2type[ (obj == null || obj !== obj )? String(obj) :  toString.call(obj)  ] || obj.nodeName || "#";
    
                if( result.charAt(0) === "#"){//              , window.opera
    
                    if(obj.window==obj){
    
                        result = 'Window'; //       
    
                    }else if(obj.nodeType === 9) {
    
                        result = 'Document';//       
    
                    }else if(  obj.callee ){
    
                        result = 'Arguments';//       
    
                    }else if(isFinite(obj.length) && obj.item ){
    
                        result = 'NodeList'; //      
    
                    }else if(obj.open && obj.send ){
    
                        result = "XMLHttpRequest";
    
                    }else{
    
                        result = toString.call(obj).slice(8,-1);
    
                    }
    
                }
    
                if(str){
    
                    return str === result;
    
                }
    
                return result;
    
            },
    
            /**
    
             *     ,   IE6        
    
             * @param {String} s       
    
             * @param {Boolean} force         
    
             */
    
            log:function(s, force){
    
                if(force || !global.console){
    
                    var div =  DOC.body && DOC.createElement("div");
    
                    if(div){
    
                        div.innerHTML = s;
    
                        DOC.body.appendChild(div)
    
                    }
    
                }else{
    
                    global.console.log(s);
    
                }
    
            },
    
            /**
    
             *          ,       
    
             * @param {Array|String} array       ,  ","     
    
             * @param {Number} val   ,   1
    
             * @return {Object}
    
             */
    
            oneObject : function(array, val){
    
                if(typeof array == "string"){
    
                    array = array.match(dom.rword) || [];
    
                }
    
                var result = {},value = val !== void 0 ? val :1;
    
                for(var i=0,n=array.length;i < n;i++){
    
                    result[array[i]] = value;
    
                }
    
                return result;
    
            }
    
        });
    
        "Boolean,Number,String,Function,Array,Date,RegExp,Window,Document,Arguments,NodeList,XMLHttpRequest".replace(dom.rword,function(name){
    
            class2type[ "[object " + name + "]" ] = name;
    
        });
    
    
    
        // http://wp.moooori.com/archives/1911
    
        var
    
        rmodule =  /([^(\s]+)\(?([^)]*)\)?/,
    
        onload= w3c ? "onload" : "onreadystatechange",
    
        names = []//          
    
        var map = dom["@modules"] = {
    
            "@ready" : { }
    
        };
    
    
    
        /**
    
         *     opera script onerror
    
         * @param {String} name    
    
         * @param {String} url       
    
         * @param {Element} node             script  
    
         */
    
        function fixOperaError(name, url, node){
    
            var iframe = DOC.createElement("iframe");
    
            var code = "<script> window[document.URL.replace(/(\W|(#.+))/g,'')] = {define:function(){} } <\/script>"+
    
            '<script src="'+url+'" onload="this.ownerDocument.x = 1;"><\/script>';
    
            iframe.style.display = "none";
    
            HEAD.appendChild(iframe);
    
            var d = iframe.contentDocument;
    
            d.write(code);
    
            d.close();
    
            iframe.onload = function(){
    
                if(d.x == void 0){
    
                    removeScript(name, node, true);
    
                }
    
                iframe.onload = null;//opera   iframe         
    
                HEAD.removeChild(this);
    
            };
    
        }
    
    
    
        /**
    
         *             script  
    
         * @param {String} name    
    
         * @param {String} url       
    
         */
    
        function appendScript(name, url){
    
            var node = DOC.createElement("script");
    
            url = url  || dom.basePath +"/"+ name.slice(1) + ".js" + (dom["debug"] ? "?timestamp="+new Date : "");
    
            node.charset = "utf-8";
    
            node.async = true;
    
            node.onerror = function(){
    
                removeScript(name, this, true);
    
            }
    
            node[onload] = function(){
    
                if (w3c || dom.rreadystate.test(this.readyState) ){
    
                    resolveCallbacks();
    
                    removeScript(name, this );
    
                }
    
            }
    
            node.src =  url;
    
            global.opera && fixOperaError(name, url, node);
    
            HEAD.insertBefore(node,HEAD.firstChild);
    
        }
    
        /**
    
         *        script  
    
         * @param {String} name    
    
         * @param {Element} node             script  
    
         * @param {Boolean} error       
    
         */
    
        function removeScript(name, node, error){
    
            var parent = node.parentNode;
    
            if(parent && parent.nodeType === 1){
    
                if(error || !map[name].state ){
    
                    dom.stack(new Function('dom.log("fail to load module [ '+name+' ]")'));
    
                    dom.stack.fire();//      
    
                }
    
                if (node.clearAttributes) {
    
                    node.clearAttributes();
    
                } else {
    
                    node[onload] = node.onerror = null;
    
                }
    
                parent.removeChild(node);
    
            }
    
        }
    
    
    
        //                  
    
        function resolveCallbacks(){
    
            loop:
    
            for (var i = names.length,repeat, name; name = names[--i]; ) {
    
                var  obj = map[name], deps = obj.deps;
    
                for(var key in deps){
    
                    if(deps.hasOwnProperty(key) && map[key].state != 2 ){
    
                        continue loop;
    
                    }
    
                }
    
                //  deps                 3
    
                if( obj.state != 2){
    
                    names.splice(i,1);//        ,   IE DOM          ,            
    
                    obj.callback();
    
                    obj.state = 2;
    
                    repeat = true;
    
                }
    
            }
    
        repeat &&  resolveCallbacks();
    
        }
    
        var deferred = function (){//         
    
            var list = [],self = function(fn){
    
                fn && fn.call && list.push(fn);
    
                return self;
    
            }
    
            self.method = "shift";
    
            self.fire = function(fn){
    
                while(fn = list[self.method]()){
    
                    fn();
    
                }
    
                return list.length ? self : self.complete();
    
            }
    
            self.complete = dom.noop;
    
            return self;
    
        }
    
        var errorstack = dom.stack = deferred();
    
        errorstack.method = "pop";
    
        mix(dom, {
    
            mix:mix,
    
            //    (   )
    
            bind : w3c ? function(el, type, fn, phase){
    
                el.addEventListener(type,fn, phase);
    
            } : function(el, type, fn){
    
                el.attachEvent("on"+type, function(){
    
                    fn.call(el,global.event);
    
                });
    
            },
    
            /**
    
         * <a href="http://www.cnblogs.com/rubylouvre/archive/2011/02/10/1950940.html">        </a>
    
         * @property
    
         * @type String
    
         */
    
            basePath:(function(url, scripts, node){
    
                scripts = DOC.getElementsByTagName("script");
    
                node = scripts[scripts.length - 1];
    
                url = node.hasAttribute ?  node.src : node.getAttribute('src', 4);
    
                return url.substr( 0, url.lastIndexOf('/'));
    
            })(),
    
            /**
    
         *     
    
         * @param {String|Array} deps     ,            ,                
    
         * @param {Function} module     
    
         * @param {Function} errback     
    
         */
    
            // dom.require("class,lang",function(){})
    
            require:function(deps,callback,errback){
    
                var _deps = {};
    
                (deps +"").replace(dom.rword,function(url,name,match){
    
                    match = url.match(rmodule);
    
                    name  = "@"+ match[1];//     
    
                    if(!map[name]){ //           
    
                        map[name] = { };//state: undefined,    ; 1    ; 2 :    
    
                        appendScript(name,match[2]);//  JS  
    
                    }
    
                    _deps[name] = "    ";//        ,    
    
                });
    
                var name = callback._name || "@cb"+ (+new Date + Math.random());
    
                dom.stack(errback);//      
    
                map[name] = {//          
    
                    callback:callback,
    
                    deps:_deps,
    
                    state: 1
    
                };
    
                names.push(name);
    
            },
    
            /**
    
         *     
    
         * @param {String} name    
    
         * @param {String} dependList     
    
         * @param {Function} module     
    
         */
    
            define:function(name,deps,callback){
    
                if(typeof deps == "function"){//           
    
                    callback = deps;
    
                    deps = "";
    
                }
    
                callback._name =  "@"+name;  //   
    
                this.require(deps,callback);
    
            }
    
        });
    
        /**
    
     * domReady  
    
     * @param {Function} fn     
    
     */
    
        var readylist = dom.ready =  deferred();
    
        function fireReady(){
    
            map["@ready"].state = 2;
    
            resolveCallbacks();//fix opera         
    
            readylist.complete = function(fn){
    
                fn && fn.call &&  fn()
    
            }
    
            readylist.fire();
    
            fireReady = dom.noop;
    
        };
    
        function doScrollCheck() {
    
            try {
    
                dom.HTML.doScroll("left");
    
                fireReady();
    
            } catch(e) {
    
                setTimeout( doScrollCheck, 1);
    
            }
    
        };
    
        //           
    
        if ( DOC.readyState === "complete" ) {
    
            fireReady();
    
        }else {
    
            dom.bind(DOC, (w3c ? "DOMContentLoaded" : "readystatechange"), function(){
    
                if (w3c || DOC.readyState === "complete") {
    
                    fireReady();
    
                }
    
            });
    
            try {
    
                //http://bugs.jquery.com/ticket/4787 http://cmc3.cn/
    
                // IE6 ,         document.domain,  window.frameElement  ,
    
                //      try catch ,      
    
                var toplevel = global.frameElement == null;
    
            } catch(e) {};
    
            if ( dom.HTML.doScroll && toplevel ) {
    
                doScrollCheck();
    
            }
    
        }
    
        //https://developer.mozilla.org/en/DOM/window.onpopstate
    
        dom.bind(global,"popstate",function(){
    
            namespace = DOC.URL.replace(/(#.+|\W)/g,'');
    
            dom.exports();
    
        });
    
        dom.exports();
    
    })(this,this.document);
    
    /**
    
     2011.7.11
    
    @           ,        ,
    
    dom.check  dom["@emitter"]
    
    dom.namespace  dom["@name"]
    
         dom.modules
    
      exports  
    
    2011.8.4
    
      dom.log, IE6      
    
      fixOperaError resolveCallbacks
    
     provide     require  
    
    2011.8.7
    
      define,require,resolve
    
      "@modules"   dom     
    
      domReady     
    
    2011.8.18
    
      HTML5 History API   “  URL     ”  , URL    namespace     !
    
    2011.8.20   dom.K,     dom.noop,            dom.ready     dom.stack
    
    2011.9.5    dom.type
    
    2011.9.19   dom.mix
    
    */
    
    

    関連リンク:
    マイモジュールロードシステムv 8
    マイモジュールロードシステムv 7
    マイモジュールロードシステムv 6
    ダウンロードアドレス:115メッシュ