我遇到了这样一种情况:我使用JavaScript动态地向页面添加脚本,最后是一个空白的白页,其中删除了正文标记。下面是代码。这段代码不是最优的,因为它在jQuery加载时添加了几次脚本,但我知道修复是什么(见注释)......我不知道的是为什么页面或者浏览器的行为方式。
function LoadingClass ()
{
this.check = function(iteration) {
var o = this;
console.log("Checking...");
if (typeof jQuery === 'undefined') {
iteration++;
console.log("jQuery not found (iteration " + iteration + ")");
if (iteration > 50) {
console.error("No jQuery found. Cannot start.");
} else {
// This code seems simple but behaves oddly
console.log("No jQuery found yet. Let's add the script.");
document.write('<script id="script_jquery" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>');
// This is the fix that prevents the script from
// being written more than once. No issue with this.
/*
if (document.getElementById('script_jquery') === null) {
console.log("No jQuery found yet. Let's add the script.");
document.write('<script id="script_jquery" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>');
} else {
console.log("No jQuery found yet, but the script exists. Waiting...");
}
*/
// Check again
var t = setTimeout(function(){ o.check(iteration); }, 100);
}
} else { // Continue with startup code here...
console.log("jQuery Loaded. Continue...");
}
};
}
window.whitepageProblem = new LoadingClass();
whitepageProblem.check(0);
当我从Chrome中的简单HTML页面运行时,我发现:
<head>
(那不应该发生!)<head>
中的其他所有内容都消失了(?!)<body>
标记(?!)如果有人愿意测试,这里有一个简单的页面......
<!doctype html>
<html>
<head>
<title>Whitepage Test</title>
<style>
body { background: #6688ff; }
</style>
</head>
<body>
<h1>Whitepage Test</h1>
<script src="whitepage.js"></script> <!-- Add the js code to this file -->
</body>
</html>
为了清楚起见,问题不在于我如何解决这个问题(尽管如果你有一个比我所包含的更好的解决方案,我很乐意听到它),但正在发生的事情这里的?
答案 0 :(得分:1)
当您在文档最初被浏览器关闭后写入文档时,效果是从一个全新的空文档开始。