2014-09-29 33 views
0

我遇到了一种情况,我正在使用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页面,我发现:

  • 的检查功能运行4或5倍(我期望)
  • 页面可见只是一瞬间(DOM负载而JavaScript是迭代
  • 脚本最终会被加入到<head>,这不是应该发生的!
  • <head>中的其他内容消失(?!
  • <body>标签无处可在开发人员工具(元素选项卡)看到(?!
  • 然而HTML源代码看起来很好

如果有人会关心测试,这里的一个简单的网页...

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

为什么你应该避免document.write()的文章http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – 2014-09-29 22:24:56

+0

谢谢。副本的相关答案很简单:“一旦文档完成加载,就不能使用document.write,如果这样做,浏览器将打开一个替代当前文档的新文档。” – Luke 2014-09-29 22:29:02

+0

而不是document.write:'var script = document.createElement('script'); script.id =“script_jquery”; script.src =“yourjQueryURL”; \t \t \t \t document.body.appendChild(script);' – Luke 2014-09-30 20:39:48

回答

1

当您在之后写入文档时,文档最初由浏览器关闭,其效果是从全新的空文档开始。