大佬教程收集整理的这篇文章主要介绍了通过库从 html/javascript 中引用 zip/tar 文件中的图像,可能吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这似乎是一个措辞相似的问题的重复。但是,主要区别有望变得明显。
不求空间效率,而是求效率。延迟加载可以满足这一点。但是,对于需要尽快同时显示内容以提供用户体验的情况,延迟加载无济于事。
HTML 服务器是否可以提供可直接访问组件的 zip 或 tar 文件? 库将在幕后执行以下操作..
用例:将在屏幕上显示为图库的 100 个缩略图的焦油球。 可能的语法可能是:
<img data-src="https://example.com/imgs.tar/img001.jpg" class="tarload" />
<script>
const obj = TarLoad()
obj.observe()
</script>
首先,这绝对不比多次请求图像更有效。浏览器实际上可以在很大程度上并行化请求(我认为 Chrome 中一次 6 个 http 请求,Firefox 中一次 31 个?不完全确定)。因此,下载数十张图像的开销与单个 TAR 的开销非常相似。不同之处在于,并行化时,可以在每个请求完成后立即渲染图像(因此先渲染较小的图像),而对于图像存档,每个图像最多可以串行渲染(通过流式传输存档),最坏的情况是在显示任何图像之前需要等待所有图像加载。此外,提取 TAR 或 ZIP 的运行时成本是不值得的,更不用说您需要下载额外的 JavaScript 才能支持此类内容。
综上所述,您所建议的绝对是可能的。您可以使用 ZIP 或 TAR 执行此操作。我不知道有什么好的流媒体解压库,但我编写了一个非常高效且小巧的流媒体解压库 fflate
。首先从 CDN 添加库:
<script src="https://cdn.jsdelivr.net/npm/fflate/umd/index.js"></script>
添加图片:
<img data-src="https://example.com/imgs.zip/img001.jpg" class="zipload" />
<img data-src="https://example.com/imgs.zip/img002.jpg" class="zipload" />
<img data-src="https://example.com/others.zip/img001.jpg" class="zipload" />
然后运行这个 JavaScript:
const zipFiles = {};
for (const img of document.querySELEctorAll('img.zipload')) {
const fullSrc = img.getAttribute('data-src');
// Finds the filepath of what to extract
const fnInd = fullSrc.indexOf('.zip/') + 4;
if (fnInd == 3) throw new Error(`Invalid data-src "${fullSrc}"`);
const zipURL = fullSrc.slice(0,fnInd);
const filepath = fullSrc.slice(fnInd + 1);
if (!zipFiles[zipURL]) zipFiles[zipURL] = {};
// Stores ZIP URLs,filepaths,and elements together
zipFiles[zipURL][filepath] = img;
}
for (const zipURL in zipFiles) {
const filepaths = zipFiles[zipURL];
// Download the ZIP
fetch(zipURL).then(async res => {
// unzip logic
const unzipper = new fflate.Unzip(async file => {
// If this is one of the images we want...
if (file.name in filepaths) {
// Read the imagE into a data stream
const imgStream = new ReadableStream({
start(controller) {
file.ondata = (err,chunk,final) => {
if (err) controller.error(err);
else {
controller.enqueue(chunk);
if (final) controller.close();
}
}
file.start();
},cancel() {
file.terminate();
}
});
// Create a blob from the stream
const blob = await (new Response(imgStream)).blob();
// Use a blob URL as the source
filepaths[file.name].src = URl.createObjectURL(blob);
}
});
// Asynchronous parallelized extraction
unzipper.register(fflate.AsyncUnzipInflatE);
// Manually push each chunk in the ZIP stream through fflate
const reader = res.body.getReader();
while (true) {
const { done,value } = await reader.read();
if (donE) {
// last chunk is empty
unzipper.push(new Uint8Array(0),truE);
break;
};
unzipper.push(value);
}
});
}
我测试了这段代码,它运行得非常好(与没有任何 ZIP 相比仍然更慢且占用更多内存,但是能够在 JavaScript 中完成所有这些工作非常酷。)
以上是大佬教程为你收集整理的通过库从 html/javascript 中引用 zip/tar 文件中的图像,可能吗?全部内容,希望文章能够帮你解决通过库从 html/javascript 中引用 zip/tar 文件中的图像,可能吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。