我怎么能在一段时间后加载JavaScript?

时间:2014-05-19 04:30:01

标签: javascript jquery

我有一个正在执行javascript的文件。我希望它在一段时间后加载。例如 - 我的脚本是<script>document.write("hello")</script>并且当我打开文件时它直接加载我希望它在一些之后加载时间约5秒。你可以帮助我,因为我是Javascript初学者。请帮我这样做。谢谢提前

3 个答案:

答案 0 :(得分:3)

您可以使用setTimeout这样的功能:

setTimeout(function() {
      // Do something after 5 seconds
}, 5000);

并且 @mplungjan 在评论中提到的一件事是,当document.write执行时,它会擦除​​文档并删除所有脚本,因此您不应该使用document.write,而不是使用{{1}} @mplungjan 发布的替代方式。

答案 1 :(得分:2)

页面加载后你不能document.write。如果这样做,页面就会被删除。

将脚本更改为以后执行非常容易。例如,将内容包装在一个函数中并更改其中的任何document.write(请显示代码)以串联连接

function concatIt() {
  var text = "";
  text += "some string previously written with document.write";
  text += "some string previously written with document.write";
  text += "some string previously written with document.write";
  return text; // send text to calling statement
}

window.onload=function() { // when page has loaded
  setTimeout(function() { 
    document.getElementById("somecontainer").innerHTML=concatIt();
  },10000); // insert after 10 seconds
}

答案 2 :(得分:1)

您可以使用 -

setTimeout(function() {

document.getElementsByTagName('body')[0].appendChild('<script>document.write("hello")</script>');

}, 5000);

基于评论 -

作为建议,您不应在文档加载后添加此类脚本。这是因为如果您使用'document.write('something')',它将删除文档中的先前内容,并将'something'写入其中。