I have a short HTML file that tries to add a one-line footer that will be common to several files by using w3IncludeHTML
. Some of the time, it works, but some of the time the last bit of HTML before the call to w3IncludeHTML
is replaced by the footer, with the end result being that the last bit is missing and the footer appears twice.
Here's my calling page:
<head>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
</head>
<body>
<a href="lessons.html">« Previous</a> • <a href="home.html"> Home </a>
<div w3-include-html="Footer.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
Here's my footer page:
Footer.
When it works, my output looks like this:
« Previous • Home Footer.
When it doesn't work, it looks like this:
« Previous • Footer. Footer.
There is no way I have found to force either behavior. Whether it works or not appears to be at random, with the error coming and going as I refresh the page over and over.
I'm using Chrome 53.0.2785.143 m and running Apache HTTP Server 2.4.7 as my localhost under Windows 10 Version 1607 Build 14393.321. (Problem may well be a Chrome issue, as IE11, FireFox 49, and Edge don't show the same behavior.)
Can anyone help me understand why this is happening? Thanks!
UPDATE:
I pulled out the JavaScript function's source and played with that a bit. The problem goes away if, at the point where the function opens an XMLHttpRequest
, it asks for the subsequent send
operation to be synchronous. This doesn't appear to be a real fix, though, as synchronous use of send
is deprecated on the main thread. I'm no JavaScript guru, so I'm don't understand why making this operation asynchronous would cause the problem I am seeing. Is it a bug in Chrome, maybe?
Here's the JavaScript (please note I have changed the name of the function and the name of the attribute it looks for, and reformatted it a bit; other than that, it is that same as w3schools' version, but for the change from true
to false
in the call to the open
method):
function xLuIncludeFile()
{
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++)
{
if (z[i].getAttribute("xlu-include-file"))
{
a = z[i].cloneNode(false);
file = z[i].getAttribute("xlu-include-file");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
a.removeAttribute("xlu-include-file");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
xLuIncludeFile();
}
}
// false makes the send operation synchronous, which solves a problem
// when using this function in short pages with Chrome. But it is
// deprecated on the main thread due to its impact on responsiveness.
// This call may end up throwing an exception someday.
xhttp.open("GET", file, false);
xhttp.send();
return;
}
}
}
答案 0 :(得分:0)
问题是由安装和启用&#34; Chrome Stylist&#34;扩展,版本2.1.0。禁用该扩展会使问题消失。