本片讲解Egret使用JSZip解析加压的js代码,然后将其还原成可执行的js代码。
一 , 先将egret库打包 :
①:在网站根目录建一个egret文件夹,在其中放入类库
②:将egret文件夹打包成egret.zip
二 , 将main.min.js打包成main.min.js.zip
三 , index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Egret</title>
<meta name="viewport" content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="full-screen" content="true" />
<meta name="screen-orientation" content="portrait" />
<meta name="x5-fullscreen" content="true" />
<meta name="360-fullscreen" content="true" />
<style>
html, body {
-ms-touch-action: none;
background: #888888;
padding: 0;
border: 0;
margin: 0;
height: 100%;
}
</style>
<script egret="libs" src="libs/modules/jszip/jszip.min.js"></script>
</head>
<body>
<div class="egret-player"
data-entry-class="Main"
data-orientation="auto"
data-scale-mode="showAll"
data-frame-rate="30"
data-content-width="640"
data-content-height="1136"
data-show-paint-rect="false"
data-multi-fingered="2"
data-show-fps="false" data-show-log="false"
data-show-fps->
</div>
<script>
//加载egret的引擎库
try
{
loadZip("egret.zip",function(zip)
{
//压缩进的egret引擎的各个代码文件
var files = ["egret.min.js", "egret.web.min.js", "res.min.js", "tween.min.js",
"dragonBones.min.js","eui.min.js","game.min.js","jszip.min.js","particle.min.js"];
for (var i = 0; i < files.length; i++)
{
createScript(zip,"egret/"+files[i]);
}
//加载游戏代码
loadZip("main.min.js.zip" + "?v=" + Math.random(),function(zip)
{
createScript(zip,"main.min.js");
//全部加载完成,启动egret游戏
egret.runEgret({ renderMode: "webgl", audioType: 0,retina:true});
});
});
}
catch (e)
{
//压缩失败,实际项目这里需要改为加载没压缩的js文件。
console.error("jszip解压文件报错,进行普通文件加载");
}
//加载单个zip文件,成功后进行回调
function loadZip(url,callBack)
{
var xhrZip = new XMLHttpRequest();
xhrZip.open("GET", url, true);
xhrZip.responseType = "arraybuffer";
xhrZip.addEventListener("load", function (oEvent)
{
var arrayBuffer = xhrZip.response; // 注意:不是oReq.responseText
if (!arrayBuffer)
{
console.log(url + "解析异常:" + xhrZip);
throw new Error("zip异常");
}
callBack(new JSZip(arrayBuffer));
});
xhrZip.send(null);
}
function createScript(zip,file)
{
//解压出来变成script脚本
var text = zip.file(file).asText();
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.text = text;
document.body.appendChild(script);
document.body.removeChild(script);
}
</script>
</body>
</html>
网站结构:
使用浏览器查看加载结果:
如果不使用压缩 , 则结果是:
可以看出加载的代价比不压缩要高很多。尤其是当项目很大时。这就是压缩js的意义。。。。。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。