Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lottie 压缩指北 #19

Open
geeeger opened this issue Aug 3, 2020 · 1 comment
Open

lottie 压缩指北 #19

geeeger opened this issue Aug 3, 2020 · 1 comment
Labels
documentation Improvements or additions to documentation

Comments

@geeeger
Copy link
Owner

geeeger commented Aug 3, 2020

web使用lottie动画,其json源代码是可以压缩的,此处我们可以摒弃或混淆以下内容

  • 元件的nm字段(渲染不需要该字段)
  • 元件的mn字段(渲染不需要该字段)
  • 元件的id字段可混淆(渲染仅需要引用)
  • 元件的refId字段可混淆(渲染仅需要引用)

基于此种思想,可以实现

const json = require('./test.json')
const fs = require('fs')
let result = []
const max = 122
const min = 97
let start2 = min
const idmap = { 
}
function walker(obj) {
    if (typeof obj !== 'object') {
        return;
    }
    for (const key in obj) {
        switch (key) {
            case 'nm':
            case 'mn':
                delete obj[key]
                break
            case 'id':
            case 'refId':
                if (!idmap[obj[key]]) {
                    let start = start2++
                    if (start > max) {
                        result.push('')
                        start = min
                        start2 = min
                    }
                    let index = result.length - 1
                    if (index < 0) {
                        index = 0
                    }
                    result[index] = start
                    idmap[obj[key]] = result.map((v) => String.fromCharCode(v)).join('')
                }
                obj[key] = idmap[obj[key]]
                break
        }
        walker(obj[key])
    }
}

walker(json)
fs.writeFileSync('./dist.json', JSON.stringify(json))

由于lottie-web依赖为200k,如果要进一步压缩,可以尝试引入zipson
zipson dist大小为21.9k
在重复结构压缩上可能可以达到最高50%的压缩率
但是考虑到100多k的动画压缩也不会小多少,再引入一个zipson貌似得不偿失

原文有新记录,请进入查看

@geeeger geeeger added the documentation Improvements or additions to documentation label Aug 3, 2020
@geeeger
Copy link
Owner Author

geeeger commented Aug 19, 2020

盲点: 发现有官方实现, https://github.com/Lottie-Lint/lottie-compress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant