loader.js 23.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
(function (g) {
    var font = {
        DEFAULT: 'default',
        BIG: 'big',
        LARGE: 'large'
    };
    
    var worker = null;
    var _createScript = function (src, onload,onerror) {
        var script = document.createElement("script");

        script.src = src;
        script.type = "text/javascript";
        script.onload = onload;
        script.onerror = onerror;
        document.head.appendChild(script);
    },_createLinkCSS = function (src, onload,onerror) {
        var link = document.createElement("link");
        link.rel =  "stylesheet";
        link.type = "text/css";
        link.href = src;
        link.onload = onload;
        link.onerror = onerror;
        document.head.appendChild(link);
    }, _get = function (url, success, fail) {
        if(location.protocol === "file:") return;

        if (window.Worker) {
            worker = new Worker("/mobilemode/mobile/dist/js/worker.js");
            
            worker.postMessage({
                action: "ajax",
                args: { url: url }
            });
            worker.onmessage = function (e) {
                success(e.data);
            };
            return;
        }

        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var responseText = xhr.responseText;

                if (xhr.status == 200) {
                    success && success(responseText);
                } else {
                    fail && fail(responseText);
                }
            }
        };
        xhr.open("GET", url, true);
        xhr.send(null);
    };
    var isSupportSW = (function () {
        var isSupportServiceWorker = "serviceWorker" in window.navigator;
        var isHttpsProtocol = window.location.protocol === "https:";
        var isLocalHost = ~["localhost", "127.0.0.1"].indexOf(window.location.hostname);

        return isSupportServiceWorker && (isHttpsProtocol || isLocalHost);
    }());

    if (isSupportSW) {
        navigator.serviceWorker.register("/mobilemode/mobile/sw.js?v=804df22b63", { scope: "/mobilemode/mobile/" }).catch(function (e) {
            // 注册失败后, 注销已存在的serviceworker
            navigator.serviceWorker.getRegistrations().then(function (registrations) {
                registrations.forEach(function (registration) {
                    registration.unregister();
                });
            });
        });
    };

    var isEnabledCache = "localStorage" in window && !isSupportSW, // 不支持PWA 则使用localStorage缓存方案
        MMSRC = "mobile_static_resource_cache";

    var mmsrc = {
        get: function () {
            return JSON.parse(localStorage.getItem(MMSRC) || "{}");
        },
        set: function (o) {
            try {
                localStorage.setItem(MMSRC, JSON.stringify(o));
            } catch (e) {
                console.log("超出localStorage上限");
            }
        }
    };

    g.Loader = function (opts) {
        opts.require.version = opts.require.path.split("v=")[1];
        opts.module.version = opts.module.path.split("v=")[1];

        var JavascriptLoader = function () {
            var r = opts.require;
            var mod = opts.module;
            var _cache = {
                get: function (m) {
                    var o = (mmsrc.get().js || {})[m.name] || {};

                    return o[m.version];
                },
                set: function (m) {
                    _get(m.path, function (code) {
                        var ms = mmsrc.get() || {}, obj = {}, js = ms.js || {};

                        obj[m.version] = code;
                        js[m.name] = obj;
                        ms.js = js;
                        mmsrc.set(ms);
                    });
                }
            };
            var _loader = {
                init: function (modName, cb) {
                    cb = cb || function () { };

                    if (!isEnabledCache) return this[modName](cb); // 不支持localStorage 不进行缓存

                    var cacheCode = _cache.get(opts[modName]);

                    // 请求并缓存
                    if (!cacheCode) {
                        return this[modName](function () {
                            _cache.set(opts[modName]);
                            cb();
                        });
                    }

                    // 直接使用缓存
                    eval.call(window, cacheCode);
                    modName === "module" && require([opts.module.name]);
                    return cb();
                },
                require: function (cb) {
                    _createScript(r.path, cb);
                },
                module: function (cb) {
                    require([mod.path], function () {
                        require([mod.name]);
                        cb && cb();
                    });
                }
            };

            return _loader.init.apply(_loader, [].slice.call(arguments));
        };

        var HtmlLoader = function () {
            var meta = window.__meta__;
            var appid = meta.appid;
            var version = meta.resourceVersion || new Date().getTime();
            var path = "/mobilemode/mobile/page/app" + appid + "/js/frame/index.js?v=" + version;
            var u = HtmlLoader.utils;
            var _setGlobal = function (htm) {
                window[opts.module.name + "_mmsrcHtml"] = htm;
            }, _onHtmlLoaded = function(html) {
                g.Loader.htmlLoaded = true;

                if (g.Loader.onHtmlLoaded) {
                    g.Loader.onHtmlLoaded(html);
                } 
            }, _getAppHomepageId = function (htmJson) {
                var id = "";

                htmJson.pages.every(function (page) {
                    if (!page.h) return true;

                    id = page.i;
                });

                return id;
            }, _setCurrentPageId = function (pageid) {
                pageid = String(pageid);

                meta.appHomepageId = ~pageid.indexOf("page_") ? pageid : "page_"+pageid;
            };

            if(!isEnabledCache) {
                return require([path], function (htmJson) {
                    var appHomepageId = meta.appHomepageId;

                    if (!appHomepageId) {
                        appHomepageId = _getAppHomepageId(htmJson);
                    }

                    _setCurrentPageId(appHomepageId);

                    html = u.toHtml(htmJson);

                    u.initRuntimeConfig(htmJson.runtime);
                    _setGlobal(html);
                    _onHtmlLoaded(html);
                });
            }
            
            var mmsrcHtmlObj = mmsrc.get().htm || { history: [] }, // history 用于存放应用模板的存放顺序 当localstorage容量不够时 取最早应用删除
                currHtmlObj = mmsrcHtmlObj[appid] || {},
                mmsrcHtml = currHtmlObj[version];

             // 只有默认字体下使用缓存
            if(mmsrcHtml && version in currHtmlObj && meta.clientFont === font.DEFAULT) {
                _setCurrentPageId(meta.appHomepageId || currHtmlObj.appHomepageId);
                u.initRuntimeConfig(JSON.parse(currHtmlObj.runtime));
                
                return _setGlobal(mmsrcHtml);
            } 

            currHtmlObj = {};

            require([path], function (htmJson) {
                var issuccess = false;
                var isdelete = false;
                var html = JSON.stringify(htmJson);
                var appHomepageId = _getAppHomepageId(htmJson);
                var _cache = function () {
                    var o = mmsrc.get();
                    try {
                        var index = mmsrcHtmlObj.history.indexOf(appid);

                        currHtmlObj[version] = html;
                        currHtmlObj.appHomepageId = appHomepageId;
                        currHtmlObj.runtime = JSON.stringify(htmJson.runtime);
                        _setGlobal(html);
                        mmsrcHtmlObj[appid] = currHtmlObj;
                        // 删除并更新histroy中的应用顺序
                        ~index && mmsrcHtmlObj.history.splice(index, 1);
                        mmsrcHtmlObj.history.push(appid);
                        o.htm = mmsrcHtmlObj;
                        mmsrc.set(o);
                        issuccess = true;
                    } catch (e) {
                        if (isdelete) return (issuccess = true);

                        var originalId = mmsrcHtmlObj.history.shift();

                        delete mmsrcHtmlObj[originalId];
                        originalId === appid && !mmsrcHtmlObj.history.length && (isdelete = true);
                        o.htm = mmsrcHtmlObj;
                        mmsrc.set(o);
                        issuccess = true;
                    }
                };

                html = u.toHtml(htmJson);

                u.initRuntimeConfig(htmJson.runtime);
                _setCurrentPageId(meta.appHomepageId || appHomepageId);

                while (!issuccess) {
                    try {
                        _cache();
                    } catch (e) {
                        _cache();
                    }
                }
                _onHtmlLoaded(html);
            });
        };

        HtmlLoader.utils = {
            map: function(pages) {
                var u = this;

                return pages.map(function(page) {
                    return {
                        id: "page_" + page.i,
                        name: page.n,
                        attrs: "class='page out'" + (page.h ? " data-homepage" : ""),
                        compHtml: page.c.reduce(function (prev, comp) { // comps
                            return prev + u.toCompTmpl(comp);
                        }, ""),
                        tabBarPageHtml: page.p && u.map(page.p).reduce(function (prev, p) { // innerPages 只有tabbar有
                            p.attrs = "class='tabpanel show_hide out' data-form='show_hide'";
                            return prev + u.toPageTmpl(p);
                        }, "") || "",
                        pageOptions: page.m ? " data-pageoptions='"+page.m.i+":"+page.m.t+":"+page.m.s+":"+page.m.l+"'" : ""
                    };
                });
            },
            toCompTmpl: function(comp) {
                if (comp.TabBar) return "";

                var attrs = "";

                if(comp.c) { // category
                    attrs += "data-category='" + comp.c + "' ";
                }

                if (comp.l) { // lazyload
                    attrs += "data-lazyload='true' ";
                }

                if (!isNaN(comp.p)) { // proirity
                    attrs += "data-priority='" + comp.p + "'";
                }

                // i => id; t => type
                return "<abbr id='" + comp.i + "' data-type='" + comp.t + "' " + attrs + " ></abbr>";
            },
            toPageTmpl: function(page) {
            	return "\
                    <div id='" + page.id + "' data-title='" + page.name + "' " + page.attrs + page.pageOptions + " >\
                        <div class='page-content' id='" + page.id + "_content'>\
                        	<div class='page-scroller' id='" + page.id + "_scroller'>" + page.compHtml + "</div>\
                            " + page.tabBarPageHtml + "\
                        </div>\
                    </div>\
                ";
            },
            toPagesTmpl: function(pages) {
                var u = this;

                return pages.reduce(function(prev, page) {
                    if(page.innerPages) {
                        prev += u.toPagesTmpl(page.innerPages);
                    }

                    return prev + u.toPageTmpl(page);
                }, "");
            },
            toHtml: function(html) {
                var meta = g.__meta__;
                var htm = "";
                var skin = html.skin;
                
                if (meta.clientFont !== font.DEFAULT) {
                    var currMainStyleLink = document.createElement('link');
                    var defaultMainStyleLink = document.querySelector('#main-default_css');
                    var after = function (ele, targetEle) {
                        if(targetEle.parentNode) {
                            targetEle.parentNode.insertBefore(ele, targetEle.nextSibling);
                        }
                    };

                    currMainStyleLink.rel = 'stylesheet';
                    currMainStyleLink.href = "/mobilemode/mobile/dist/css/main-" + meta.clientFont + ".css?v=" + meta.resourceVersion;

                    after(currMainStyleLink, defaultMainStyleLink);
                    defaultMainStyleLink.setAttribute('media', 'none');
                }

                if (skin) {
                    htm += "<link rel='stylesheet' href='/mobilemode/skin/" + skin.id + "/_.css?v=" + skin.version + "' />";
                }

                if (html.custom_css) {
                    htm += "<link rel='stylesheet' href='/mobilemode/mobile/page/app" + meta.appid + "/css/custom/index.css?v=" + meta.resourceVersion + "' />";
                }

                htm += this.toPagesTmpl( this.map(html.pages) );

                return htm;
            },
            initRuntimeConfig: function (runtime) {
                if (!runtime) return;

                var config = runtime.config;
                var modules = runtime.modules;
                var meta = window.__meta__;
                var compos = modules.compos || [];
                var fontsExp = new RegExp('-(' + Object.keys(font).join('|') + ')', 'gi');
                var addFontExt = function (name) {
                    // 重置localStorage缓存中config已处理的字体
                    var matchs = name.match(fontsExp);

                    if (matchs) {
                        name = name.replace(matchs[0], '');
                    }
                    
                    return name + '-' + meta.clientFont;
                };

                // 系统插件
                compos.forEach(function (name) {
                    config.paths[name] = "js/component/" + name + "_wev8";
                    config.paths[name + "_css"] = addFontExt("css/component/" + name);
                });
                // 自定义插件
                (modules.custom_compos || []).forEach(function (name) {
                    config.paths[name] = "js/component/" + name + "_wev8";
                    config.paths[name + "_css"] = "css/component/" + name + '-' + font.DEFAULT;
                });

                (modules.servs || []).forEach(function(name) {
                    var mname = "mService/" + name;
                    var fname = 'service.' + name.replace('/', '.');

                    config.paths[mname] = "js/service/" + fname + "_wev8";

                    if (~name.indexOf('/')) return;

                    config.paths[mname + "_css"] = addFontExt("css/service/" + fname);
                });

                // format common中的css路径
                Object.keys(config.paths).forEach(function(modName) {
                    var relPath = config.paths[modName];

                    if (~modName.indexOf('_css') && ~relPath.indexOf('css/common')) {
                        relPath = relPath.replace(/_wev8$/, '');
                        
                        config.paths[modName] = addFontExt(relPath);
                    }
                });
                
                require(config);
            }
        };

        var initMeta = function (cb) {
            var meta = window.__meta__;
            var url = "/mobilemode/mobile/server.jsp?invoker=com.api.mobilemode.web.mobile.service.MobileEntranceAction&action=meta" +
            		"&appid=" + meta.appid + "&appHomepageId=" + meta.appHomepageId + "&mTokenFrom=" + (meta.mTokenFrom||"") + "&mToken=" + (meta.mToken||"") + "&timeZoneOffset=" + new Date().getTimezoneOffset();

            _get(url, function (result) {
                result = JSON.parse(result);
                
                if (result.status == 1) {
                	for(var name in result.data){
                    	window.__meta__[name] = result.data[name];
                    }
                } else {
                    document.write(result.errMsg);
                }
                cb();
            });
        };
        
        var util = {
            isEmobile: function () {
                return !!navigator.userAgent.match(/e-mobile/i);
            },
            isEmobile6: function () {
                return this.isEmobile() && !this.isEmobile7();
            },
            isEmobile7: function () {
                return !!navigator.userAgent.match(/e-mobile(7|\/7)/i);
            },
            checkEmpJsApi: function(name){
                return !this.isEmobile6() && window.em && typeof(em.checkJsApi) === 'function' && em.checkJsApi(name);
            },
            invokeEmApi: function(name){
                var args = [].slice.call(arguments).slice(1);
                
                em.ready(function(){
                    em[name].apply(em, args);
                });
            }
        };
        
        var initClientInfo = function (cb) {
            var _setClientInfo = function (info) {
                window.__meta__.clientFont = info.clientFont;
                window.__meta__.clientTheme = info.clientTheme;	
                window.__meta__.clientDeviceId = info.clientDeviceId;
                cb();
            };

            if (!util.checkEmpJsApi("getClientInfo")) {
                _setClientInfo({ clientFont: font.DEFAULT, clientTheme: window.__meta__.clientTheme });
            } else {
                util.invokeEmApi("getClientInfo", {
                    success: function (res) {
                        var clientFont = font.DEFAULT;
                        switch(res.clientFont) {
                            case "1":
                                clientFont = font.DEFAULT; break;
                            case "2":
                                clientFont = font.BIG; break;
                            case "3":
                                clientFont = font.LARGE; break;
                            default:
                                clientFont = font.DEFAULT; break;
                        }
                        var clientTheme = res.clientTheme || window.__meta__.clientTheme;
                        var clientDeviceId = res.deviceId;
                        _setClientInfo({
                            clientFont: clientFont,
                            clientTheme: clientTheme,
                            clientDeviceId: clientDeviceId
                        });
                    }
                });
            } 
        };

        var staticResourceLoad = function () {
            var resourceQueue = {
                arr:[],
                excuteNextMethod : function () {if( this.arr.length > 0) return this.arr.shift()();},
                addLoadMethod:function (cb) {this.arr.push(cb);}
            };
            (window.__meta__.staticResources||[]).map(function(r){
                resourceQueue.addLoadMethod(function () {
                    var cb = function(){ resourceQueue.excuteNextMethod();};
                    r.type == 'JS' && _createScript(r.path,cb,cb);
                    r.type == 'CSS' && _createLinkCSS(r.path,cb,cb);
                });
            });
            resourceQueue.excuteNextMethod();
        };

        var initRequireConfig = function() {
            var config = window.amdConfig;
            var meta = window.__meta__;
            var newConfig = { paths: {} };

            // 处理service页面css配置
            Object.keys(config.paths).filter(function(key) {
                var path = config.paths[key];

                return ~key.indexOf('_css') && ~path.indexOf("css/service/");
            }).forEach(function(key) {
                var serviceId = key.replace(/(mService\/|_css)/g, '');

                newConfig.paths[key] = "css/service/service." + serviceId + '-' + meta.clientFont;
            });
            // 处理common和插件css配置
            Object.keys(config.paths).forEach(function(modName) {
                var relPath = config.paths[modName];

                if (~modName.indexOf('_css') && (~relPath.indexOf('css/common') || ~relPath.indexOf('css/component'))) {
                    newConfig.paths[modName] = relPath + '-' + meta.clientFont;
                }
            });
            require(newConfig);
            window.amdConfig = null;
        };
        
        var initCssVar = function(){
        	var meta = window.__meta__;
        	document.querySelector(':root').style.setProperty('--themeColor', meta.clientTheme);
        	var hd;
        	if(meta.clientFont == font.BIG){
        		hd = "16/14";
        	}else if(meta.clientFont == font.LARGE){
        		hd = "18/14";
        	}else{
        		hd = "1";
        	}
        	document.querySelector(':root').style.setProperty('--hd', hd);
        };
        
        var initWechatUserInfo = function(cb){
        	var meta = window.__meta__;

            if(~meta.wechatUser.openid.indexOf("EB_USERKEY")) {
                meta.wechatUser = {
                    openid: "",
                    nickname: "",
                    avatar: ""
                };
            }

        	if(!meta.emOpenUrl){
        		cb();
        		return;
        	}
        	
        	var invokeGetCpUser = function(){
        		if(window.em.checkJsApi("getCpUser")){
        			window.em.getCpUser({
        	            success: function(res){
        	            	meta.wechatUser.openid = res.openUserId;
        	            	meta.wechatUser.nickname = res.userName;
        	            	meta.wechatUser.avatar = res.avatar;
        	            	cb();
        	            },
        	            fail:function(error){
        	            	cb();
        	            }
        			});
        		}else{
        			cb();
        		}
        	};
        	
        	if(window.em){
        		invokeGetCpUser();
        	}else{
                var ua = window.navigator.userAgent;
                var loadJem = (/.*E-Mobile7.*/.test(ua)
                    || /.*E-Mobile\/7.*/.test(ua)
                    || /.*MicroMessenger.*/.test(ua)
                );
                if(loadJem){
                    var emUrl = meta.emOpenUrl + '/open/js/jem.js?v=' + new Date().getTime();
                    _createScript(emUrl, function() {
                        invokeGetCpUser();
                    }, function() {
                        cb();
                    });
                } else {
                    cb();
                }
        	}
        	
        };

        var initPage = function () {
        	
            initClientInfo(function () {
            	initWechatUserInfo(function(){
            		initCssVar(); 
                    staticResourceLoad();
                    initRequireConfig();
                    HtmlLoader();
                    JavascriptLoader("module");
                    g.Loader.onFinished();
            	});
            });
        };

        JavascriptLoader("require", function () {
            require(window.amdConfig);

            require(["ssoInit"], function(ssoInit){
                ssoInit.init(function () {
                    if (!window.__meta__.resourceVersion) {
                        initMeta(initPage);
                    } else {
                        initPage();
                    }
                });
            });
        });
    };


    // 页面渲染机制执行完成事件(main模块还未执行) 用于外部重写
    g.Loader.onFinished = function () {}
}(window));