javascript Mime类型为“text/html”的blob的用例是什么?

h6my8fg2  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(163)

有许多使用Mime类型text/javascriptapplication/jsonimage/...等的blob的用例示例
MDN Bolob()示例还显示:

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

上面的例子包含一个HTML片段?

  • 它可以以任何方式附加到DOM中吗(作为Blob或在获得对象URL之后)?
  • (请提供代码片段示例以展示用例。)*
    ********************重点特别放在上述用例上。

更新

根据Bergi的要求:

Blob {type: "text/javascript"}用例
// import module
(async () => {

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

})();
Blob {type: "application/json"}用例

Import Attributes为准

// import 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'}});
  
})();
Blob {type: "image/..."}用例
// include remote image
(async () => {

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

})();
laximzn5

laximzn51#

具有“text/html”MIME类型的Blob可以用于存储和传输表示网页的HTML内容。这允许您动态生成或获取HTML内容并在Web浏览器中显示。
更新:
一个<iframe>的例子,这样你就可以从一个MIME类型为“text/html”的blob中显示或注入HTML内容到网页的DOM中。

// Assuming you have retrieved the blob
var blob = ...;

// Create a Blob URL
var blobUrl = URL.createObjectURL(blob);

// Create an <iframe> element
var iframe = document.createElement('iframe');

// Set the src attribute to the Blob URL
iframe.src = blobUrl;

// Append the <iframe> to the DOM
document.body.appendChild(iframe);

相关问题