2011-11-25 78 views
1

我遇到了问题,当我想在html标记中使用document.getElementById();时。 例如=如何在javascript中优先执行dom

<html> 
<head> 
<script type="js"> //note this example is not found so browser is take time to execution 
<script type="js"> //note this example is not found so browser is take time to execution 
<script type="js"> //note this example is not found so browser is take time to execution 
<script type="js"> //note this example is not found so browser is take time to execution 
</head> 
<body> 
<div> ... 
<div id="test"> 
</div> 
</body> 
</html> 

我的问题是如何执行document.getElementById("test");无需等待加载脚本没有发现?,可以使更多的time.how我可以修复this.thanks你的答案。

注:解决不删除或修改脚本到找到的目录。 以防万一,如果脚本没有找到。

回答

1

defer="defer"添加到那些您希望推迟执行的<script />标签。

注:因为我的浏览器也执行脚本没有找到推迟对IE和Firefox的新版本和Chrome

+0

任何其他建议的作品。我只想优先'document.getElementById(“test”);'是第一次执行,我可以得到innerHTML。 – viyancs

+0

将你的JS文件加载到页面底部总是更好。看到为什么它最好加载在最后:http://stackoverflow.com/questions/1638670/javascript-at-bottom-top-of-web-page。请注意,没有'',它应该是''script type =“text/javascript”src =“path/to/your/js/file”>' –

+0

ah ya我已更新。 – viyancs

1

尝试使用headJS这将加载您的脚本异步和document.ready后。

另一种选择是将srctype移动到文件的底部,以便最后加载它们。但我不认为document.ready将被执行,直到该浏览器加载这些文件

1

假设<srctype>应该是<script>,那你要问的是你可以做的被引用不存在的脚本是什么从一个页面中,唯一可能的答案是您切换到动态脚本加载方法,如LABjs或其他,或者,当然,停止包含引用不存在的脚本的脚本标记。

浏览器将始终尝试加载并运行<script>未标记为“异步”的标记,当然这是一个相当新的属性,即使支持它的浏览器的行为也不完全一致。