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

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

I want home.html to load in

15条回答
  • 2020-11-22 09:19

    I saw this and thought it looked quite nice so I ran some tests on it.

    It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.

    I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.

    In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.

    Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="content"></div>
        <script>
            /**
            * Test harness to find out the best method for dynamically loading a
            * html page into your app.
            */
            var test_times  = {};
            var test_page   = 'testpage.htm';
            var content_div = document.getElementById('content');
    
            // TEST 1 = use jQuery to load in testpage.htm and time it.
            /*
            function test_()
            {
                var start = new Date().getTime();
                $(content_div).load(test_page, function() {
                    alert(new Date().getTime() - start);
                });
            }
    
            // 1044
            */
    
            // TEST 2 = use <object> to load in testpage.htm and time it.
            /*
            function test_()
            {
                start = new Date().getTime();
                content_div.innerHTML = '<object type="text/html" data="' + test_page +
                '" onload="alert(new Date().getTime() - start)"></object>'
            }
    
            //1579
            */
    
            // TEST 3 = use httpObject to load in testpage.htm and time it.
           function test_()
           {
               var xmlHttp = new XMLHttpRequest();
    
               xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    {
                       content_div.innerHTML = xmlHttp.responseText;
                       alert(new Date().getTime() - start);
                    }
                };
    
                start = new Date().getTime();
    
                xmlHttp.open("GET", test_page, true); // true for asynchronous
                xmlHttp.send(null);
    
                // 1039
            }
    
            // Main - run tests
            test_();
        </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 09:19

    This is usually needed when you want to include header.php or whatever page.

    In Java it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Java function in script tag.

    In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php I.e convert the php include function to Java function in script tag and place all your content in that included file.

    0 讨论(0)
  • 2020-11-22 09:21

    Fetch API

    function load_home (e) {
        (e || window.event).preventDefault();
    
        fetch("http://www.yoursite.com/home.html" /*, options */)
        .then((response) => response.text())
        .then((html) => {
            document.getElementById("content").innerHTML = html;
        })
        .catch((error) => {
            console.warn(error);
        });
    } 
    

    XHR API

    function load_home (e) {
      (e || window.event).preventDefault();
      var con = document.getElementById('content')
      ,   xhr = new XMLHttpRequest();
    
      xhr.onreadystatechange = function (e) { 
        if (xhr.readyState == 4 && xhr.status == 200) {
          con.innerHTML = xhr.responseText;
        }
      }
    
      xhr.open("GET", "http://www.yoursite.com/home.html", true);
      xhr.setRequestHeader('Content-type', 'text/html');
      xhr.send();
    }
    

    based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function

    Reference - davidwalsh

    MDN - Using Fetch

    JSFIDDLE demo

    0 讨论(0)
提交回复
热议问题