如何把一个10M的外部js文件分割为多个不到100k的文件?

如题所述:
如何把一个10M的外部js文件分割为每个不到200k的文件?,然后在通过请求这些不到200K的多个文件,把返回的内容再拼接成原文件js文件的内容?

哪个大佬能根据以下的js文件,写一个分割和组合的demo,学习一下

附上JS文件:

https://cdn.jsdelivr.net/gh/t...

阅读 3.2k
3 个回答

这太简单了。都不用分割文件。

'Range':'bytes=0-1000' 应该就可以满足你。

image.png

show = function(arrayBuffer){
    const dataView = new DataView(arrayBuffer)
    let str = ''
    for(var i = 0; i<dataView.byteLength;i++){
        if(i%8==0) str+='\n'
        str += dataView.getUint8(i).toString(2).padStart(8, '0') + ',';
    }
    console.log(str)
    return arrayBuffer
}
fetch(`https://cdn.jsdelivr.net/gh/taro99/cdn-stimulSoft@1.0.6/stimulsoft.reports.js`,{
    headers: {
        'Range':'bytes=0-160'
    }
})
    .then(v=>v.arrayBuffer())
    .then(v=>show(v))
    .then(v=>console.log('bytes=0-160', v))

fetch(`https://cdn.jsdelivr.net/gh/taro99/cdn-stimulSoft@1.0.6/stimulsoft.reports.js`,{
    headers: {
        'Range':'bytes=161-320'
    }
})
    .then(v=>v.arrayBuffer())
    .then(v=>show(v))
    .then(v=>console.log('bytes=161-320', v))


fetch(`https://cdn.jsdelivr.net/gh/taro99/cdn-stimulSoft@1.0.6/stimulsoft.reports.js`,{
    headers: {
        'Range':'bytes=0-320'
    }
})
    .then(v=>v.arrayBuffer())
    .then(v=>show(v))
    .then(v=>console.log('bytes=0-320', v))

你自己用 0-160 的去比对,看看是不是都对。

这样并不能减少请求时间,有什么意义吗?gzip压缩到2M就可以了。

补充下 @linong 回答的后续 怎么使用这些string
有三种方式
1: eval

eval("(function () {console.log('我被eval 执行了,我是当前执行的作用域')})()")
window.eval("(function () {console.log('我被eval 执行了,但是我是window作用域')})()")
window.eval.call(xxx, "(function () {console.log('我被eval 执行了,但是我是xxx作用域')})()")

2: new Function

const func = Function("(function () {console.log('我被new Function 执行了,我是window作用域')})()")
func.call(window)

3: Blob && createObjectURL

const blob = new Blob(["(function () {console.log('我被执行了,我是window作用域')})()"], {type: 'text/javascript',})
const url = URL.createObjectURL(blob)
const scriptElement = document.createElement('script')
scriptElement.src = url
scriptElement.onload = () => {URL.revokeObjectURL(url)}
document.body.appendChild(scriptElement)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题