背景說明
早期公司需要開發(fā)一款移動端App,由于原生開發(fā)成本較大,最終公司決定采用H5+cordova實現(xiàn)web打包App,隨之而來的是不斷的性能優(yōu)化,這里著重講下首屏優(yōu)化,即首次打開應用消耗時間的優(yōu)化。
優(yōu)化思路
App應用安裝時候,將首屏所需靜態(tài)資源下載到本地文件中
基本概念
預初始化CordovaWebView,移除并沒有用的cordova插件
預加載preload.html, 以及公共js,頁面中不包含業(yè)務邏輯
預注入cordova(IOS)
當開始跳轉(zhuǎn)后取出已經(jīng)預加載完的preload.html, 并加載業(yè)務JS代碼, 同時開始執(zhí)行業(yè)務邏輯和渲染業(yè)務界面
[站外圖片上傳中...(image-8cb7fd-1592830410201)]
前端核心代碼
(function (window) {
var deviceReady = false;
window.wdPreload = {
ready: function (success) {
if (deviceReady) {
success();
} else {
document.addEventListener(""deviceready"", function () {
deviceReady = true;
success();
}, false);
}
},
loadScript: function (url, callback) {
var script = document.createElement(""script"");
script.type = ""text/javascript"";
script.async = true;
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == ""loaded"" || script.readyState == ""complete"") {
script.onreadystatechange = null;
callback && callback();
}
};
} else {
script.onload = callback;
}
script.src = url;
(document.body || document.getElementsByTagName(""body"")[0] || document.documentElement).appendChild(
script);
},
formatUrl: function (url) {
var str = url.replace(/(.*\.html)?(.*?)/, '$1,$2');
var arr = str.split(',');
var indexs = [arr[1].indexOf('?'), arr[1].indexOf('#')];
var path = indexs[1] > indexs[0] ? (arr[1].slice(indexs[1], arr[1].length) + arr[1].slice(indexs[
0], indexs[1])) : arr[1];
return path;
},
appendQuery: function (url, query) {
return url + (url.indexOf('?') > -1 ? '&' : '?') + query;
},
load: function () { // 業(yè)務邏輯加載
if (location.href.indexOf('jscallback=loadScript') > -1) {
window.WDS = window.WDS || {};
wdPreload.ready(function () {
wdPreload.loadScript('index.js');
});
} else {
window.WDS = window.WDS || {};
window.WDS.nativeLoad = function (url, data) { // 此函數(shù)由APP主動調(diào)用
location.replace((location.search ? 'preload.html' : '') + wdPreload.appendQuery(wdPreload.formatUrl(
url), ""jscallback=loadScript"") + location.search.replace('?', '&'));
wdPreload.loadScript('index.js');
}
}
}
};
window.wdPreload.load();
})(window);