如何使用JavaScript在中加载HTML页面?[英]How do I load an HTML page in a using JavaScript? 本文翻译自  Giliweed  查看原文  2013-07-14  459076    html/

时间:2022-09-04 09:05:02

I want home.html to load in <div id="content">.

我想要回家。在

中加载html。

<div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div>
<div id ="content"> </div>
<script>
      function load_home(){
            document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
  }
</script>

This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?

当我使用Firefox时,这很好用。当我使用谷歌Chrome时,它会要求插件。如何让它在谷歌Chrome中工作?

10 个解决方案

#1


153  

I finally found the answer of my problem. The solution is

我终于找到了我问题的答案。解决方案是

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

#2


52  

You can use the jQuery load function:

可以使用jQuery load函数:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

对不起。编辑为on click而不是on load。

#3


30  

USING A PROMISE (fetch API)

使用一个承诺(获取API)

function fetch_text (url) {
    return fetch(url).then((response) => (response.text()));
}

Then you could chain to the results like so:

然后你可以像这样对结果进行链结:

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

Reference - davidwalsh

引用——davidwalsh

MDN - Using Fetch

MDN——使用取回

OLD ANSWER

旧的答案

Since you are looking to load html contents you should try to use an iframe and make sure that your javascript is loaded before the markup that calls the load_home() function

由于希望加载html内容,所以应该尝试使用iframe,并确保在调用load_home()函数的标记之前加载javascript

EDIT: based on your constraints I edited the javascript to use ajax instead of an iframe. try this

编辑:基于您的限制,我编辑了javascript以使用ajax而不是iframe。试试这个

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();
}

JSFIDDLE demo

JSFIDDLE演示

#4


16  

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.

这似乎是一种干净的方法,但就性能而言,与使用jQuery加载函数或使用XMLHttpRequest的普通javascript方法加载页面的时间相比,它落后了50%。

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.

我想这是因为它在后台以完全相同的方式获取页面但它也必须处理构造一个全新的HTMLElement对象。

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.

总之,我建议使用jQuery。语法尽可能地易于使用,并且它有一个结构良好的回调供您使用。它的速度也相对较快。普通的方法可能会比普通的方法快几个毫秒,但是语法却很混乱。我只在无法访问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:

这是我用来测试的代码——它是相当初级的,但是在多次尝试之后,时间返回非常一致,所以我认为在每种情况下,精确到+- 5ms。测试是在我自己的家庭服务器上运行的:

<!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>

#5


5  

When using

当使用

$("#content").load("content.html");

Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

然后请记住,您不能在chrome本地“调试”,因为XMLHttpRequest不能加载——这并不意味着它不能工作,它只是意味着您需要在相同的域中(aka)测试代码。你的服务器

#6


4  

You can use the jQuery :

您可以使用jQuery:

$("#topBar").on("click",function(){
        $("#content").load("content.html");
});

#7


0  

There is this plugin on github that load content into an element. Here is the repo

github上有一个插件将内容加载到一个元素中。这是回购

https://github.com/abdi0987/ViaJS

https://github.com/abdi0987/ViaJS

#8


-1  

Assuming I'm understanding your question correctly and you want to load the content of home.html into a div without using an outside library such as jQuery, then you might be better off using an iFrame.

假设我正确地理解了你的问题,你想要载入家庭的内容。不使用外部库(如jQuery)将html放入div中,那么最好使用iFrame。

You should be able to style the iFrame like a Div, and load the src on the click event. Or if you want to get tricky, use a hidden iFrame and pass the results of the src back to the javascript -- this can only be done if you are on the same domain though.

您应该能够将iFrame样式设置为Div,并在单击事件上加载src。或者,如果你想让事情变得棘手,可以使用一个隐藏的iFrame,将src的结果传递给javascript——这只能在相同的域上完成。

#9


-1  

showhide.html

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

#10


-3  

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

如果html文件位于本地,那么选择iframe而不是标记。标签不能跨浏览器工作,主要用于Flash

For ex : <iframe src="home.html" width="100" height="100"/>

例:

#1


153  

I finally found the answer of my problem. The solution is

我终于找到了我问题的答案。解决方案是

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

#2


52  

You can use the jQuery load function:

可以使用jQuery load函数:

<div id="topBar">
    <a href ="#" id="load_home"> HOME </a>
</div>
<div id ="content">        
</div>

<script>
$(document).ready( function() {
    $("#load_home").on("click", function() {
        $("#content").load("content.html");
    });
});
</script>

Sorry. Edited for the on click instead of on load.

对不起。编辑为on click而不是on load。

#3


30  

USING A PROMISE (fetch API)

使用一个承诺(获取API)

function fetch_text (url) {
    return fetch(url).then((response) => (response.text()));
}

Then you could chain to the results like so:

然后你可以像这样对结果进行链结:

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

Reference - davidwalsh

引用——davidwalsh

MDN - Using Fetch

MDN——使用取回

OLD ANSWER

旧的答案

Since you are looking to load html contents you should try to use an iframe and make sure that your javascript is loaded before the markup that calls the load_home() function

由于希望加载html内容,所以应该尝试使用iframe,并确保在调用load_home()函数的标记之前加载javascript

EDIT: based on your constraints I edited the javascript to use ajax instead of an iframe. try this

编辑:基于您的限制,我编辑了javascript以使用ajax而不是iframe。试试这个

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();
}

JSFIDDLE demo

JSFIDDLE演示

#4


16  

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.

这似乎是一种干净的方法,但就性能而言,与使用jQuery加载函数或使用XMLHttpRequest的普通javascript方法加载页面的时间相比,它落后了50%。

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.

我想这是因为它在后台以完全相同的方式获取页面但它也必须处理构造一个全新的HTMLElement对象。

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.

总之,我建议使用jQuery。语法尽可能地易于使用,并且它有一个结构良好的回调供您使用。它的速度也相对较快。普通的方法可能会比普通的方法快几个毫秒,但是语法却很混乱。我只在无法访问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:

这是我用来测试的代码——它是相当初级的,但是在多次尝试之后,时间返回非常一致,所以我认为在每种情况下,精确到+- 5ms。测试是在我自己的家庭服务器上运行的:

<!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>

#5


5  

When using

当使用

$("#content").load("content.html");

Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

然后请记住,您不能在chrome本地“调试”,因为XMLHttpRequest不能加载——这并不意味着它不能工作,它只是意味着您需要在相同的域中(aka)测试代码。你的服务器

#6


4  

You can use the jQuery :

您可以使用jQuery:

$("#topBar").on("click",function(){
        $("#content").load("content.html");
});

#7


0  

There is this plugin on github that load content into an element. Here is the repo

github上有一个插件将内容加载到一个元素中。这是回购

https://github.com/abdi0987/ViaJS

https://github.com/abdi0987/ViaJS

#8


-1  

Assuming I'm understanding your question correctly and you want to load the content of home.html into a div without using an outside library such as jQuery, then you might be better off using an iFrame.

假设我正确地理解了你的问题,你想要载入家庭的内容。不使用外部库(如jQuery)将html放入div中,那么最好使用iFrame。

You should be able to style the iFrame like a Div, and load the src on the click event. Or if you want to get tricky, use a hidden iFrame and pass the results of the src back to the javascript -- this can only be done if you are on the same domain though.

您应该能够将iFrame样式设置为Div,并在单击事件上加载src。或者,如果你想让事情变得棘手,可以使用一个隐藏的iFrame,将src的结果传递给javascript——这只能在相同的域上完成。

#9


-1  

showhide.html

showhide.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript">
        function showHide(switchTextDiv, showHideDiv)
        {
          var std = document.getElementById(switchTextDiv);
          var shd = document.getElementById(showHideDiv);
          if (shd.style.display == "block")
          {
            shd.style.display = "none";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
          }
          else
          {
            if (shd.innerHTML.length <= 0)
            {
              shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
            }
            shd.style.display = "block";
            std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
          }
        }
      </script>
    </head>
    <body>
      <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
        <span style="display: block; background-color: yellow">Show</span>
      </a>
      <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
    </body>
</html>

showhide_embedded.html

showhide_embedded.html

<!DOCTYPE html>
<html>
    <head>
      <script type="text/javascript"> 
        function load()
        {
          var ts = document.getElementById("theString");
          ts.scrollIntoView(true);
        }
      </script>
    </head>
    <body onload="load()">
      <pre>
        some text 1
        some text 2
        some text 3
        some text 4
        some text 5
        <span id="theString" style="background-color: yellow">some text 6 highlight</span>
        some text 7
        some text 8
        some text 9
      </pre>
    </body>
</html>

#10


-3  

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

如果html文件位于本地,那么选择iframe而不是标记。标签不能跨浏览器工作,主要用于Flash

For ex : <iframe src="home.html" width="100" height="100"/>

例: