You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MIME类型为text/html的Blob有哪些应用场景?附代码示例

Blob有很多基于不同MIME类型的应用场景,比如text/javascript、application/json、image/...等。

MDN上的Blob()示例给出了这段代码:

const array = ['<q id="a"><span id="b">hey!</span></q>']; // 仅包含单个字符串的数组
const blob = new Blob(array, { type: "text/html" }); // 创建Blob对象

这段代码生成的是包含HTML片段的Blob,能不能把它追加到DOM里?不管是直接用Blob形式,还是先获取对象URL都可以。

(请提供代码片段展示这个应用场景。)

注意:问题不涉及MIME类型的定义,重点是上述Blob的实际应用。

更新内容

根据要求补充以下不同MIME类型的Blob应用场景:

MIME类型为text/javascript的Blob应用场景

// 导入模块
(async () => {

  const response = await fetch('模块地址');
  const blob = await response.blob(); 
  // Blob { size: 10176, type: "text/javascript" }
  const url = URL.createObjectURL(blob);
  const obj = import(url);

})();

MIME类型为application/json的Blob应用场景

需遵循Import Attributes规范

// 导入JSON
(async () => {

  const blob = new Blob(['{ .... }'], {type: 'application/json'});
  // Blob { size: 10176, type: "application/json" }
  const url = URL.createObjectURL(blob);
  const obj = import(url, {with: {type: 'json'}});
  
})();

MIME类型为image/...的Blob应用场景

// 加载远程图片
(async () => {

  const response = await fetch('图片地址');
  const blob = await response.blob(); 
  // Blob { size: 10176, type: "image/png" }
  const url = URL.createObjectURL(blob);
  const img = document.createElement('img');
  img.src = url;
  document.body.appendChild(img);

})();

补充:HTML类型Blob追加到DOM的实现

针对开头提到的HTML片段Blob,这里提供两种将其插入DOM的方法:

方法1:用FileReader读取内容后直接插入

const array = ['<q id="a"><span id="b">hey!</span></q>'];
const blob = new Blob(array, { type: "text/html" });

const reader = new FileReader();
reader.onload = function(e) {
  const container = document.createElement('div');
  container.innerHTML = e.target.result;
  document.body.appendChild(container);
};
reader.readAsText(blob);

方法2:创建对象URL后通过iframe加载

const array = ['<q id="a"><span id="b">hey!</span></q>'];
const blob = new Blob(array, { type: "text/html" });

const url = URL.createObjectURL(blob);
const iframe = document.createElement('iframe');
iframe.src = url;
iframe.style.border = 'none';
iframe.style.width = '100%';
document.body.appendChild(iframe);

// 资源加载完成后释放对象URL,避免内存泄漏
iframe.onload = function() {
  URL.revokeObjectURL(url);
};

内容的提问来源于stack exchange,提问作者erosman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:47:50