How do I load an HTML page in a
using JavaScript?

后端 未结 15 2228
醉话见心
醉话见心 2020-11-22 08:29

I want home.html to load in

15条回答
  •  暖寄归人
    2020-11-22 09:08

    Fetching HTML the modern Javascript way

    This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.

    /**
      * @param {String} url - address for the HTML to fetch
      * @return {String} the resulting HTML string fragment
      */
    async function fetchHtmlAsText(url) {
        return await (await fetch(url)).text();
    }
    
    // this is your `load_home() function`
    async function loadHome() {
        const contentDiv = document.getElementById("content");
        contentDiv.innerHTML = await fetchHtmlAsText("home.html");
    }
    

    The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:

    async function fetchHtmlAsText(url) {
        const response = await fetch(url);
        return await response.text();
    }
    

    See the fetch API documentation for more details.

提交回复
热议问题