簡體   English   中英

使用 fetch 將本地 HTML 頁面導入到另一個 HTML 頁面

[英]Importing local HTML page with fetch into another HTML page

基本上,我有一個名為panel的 html 文件,其中包含一個簡單的 DIV,我想將其插入到另一個主 HTML 文件中。

我想實現一個簡單的解決方案,而不是使用 web 組件,如本答案中所述

所以,這是我正在做的測試(只是將面板記錄到控制台):

面板.html

<div id="panel">
    <h1>It works...</h1>
</div>

獲取模板.ts

export async function getTemplate(filepath: string, selectors: string) {
    let response = await fetch(filepath);
    let txt = await response.text();

    let html =  new DOMParser().parseFromString(txt, 'text/html');

    return html.querySelector(selectors);
}

主文件

import { getTemplate } from './get-template'

getTemplate('/path/to/panel.html','#panel').then((panel) => {console.log(panel);})

控制台記錄“null”。

如果此信息可以產生任何影響,我將使用parcel-bundler 來構建應用程序。

實際問題是由@CBroe確定的,是關於當parcel構建我的應用程序時,我的panel.html資源的文件路徑更改為相對於構建的dist文件夾的事實。

只是為了澄清:

  • 在構建路徑之前是相對於main.ts文件的
  • 構建后的路徑是相對於dist文件夾的

所以解決方案是考慮panel.html最終會有的URL,在用parcel構建之前提前參考。

在我的情況下,這樣的事情會起作用:

main.ts(新)

import { getTemplate } from './get-template'

getTemplate('./panel.html','#panel').then((panel) => {console.log(panel);})

那么當然,下一步就是將實際的panel.hml文件復制到dist目錄中,否則 URL 將指向一個不存在的文件。

我看到有一個關於在parcel存儲庫中自動復制靜態(或資產)文件的github問題,提供的解決方案之一是使用插件parcel-plugin-static-files-copy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM