我怎么能加载javascript一段时间后

How can i load javascript after some time?

本文关键字:一段时间 javascript 加载 怎么能      更新时间:2023-09-26

我有一个正在执行javascript的文件。我想让它在一段时间后加载。例如,我的脚本是<script>document.write("hello")</script>,当我打开文件时,它直接加载,我希望它在大约5秒后出现。你能帮助我,因为我是Javascript初学者。请帮我做这件事。提前感谢

setTimeout函数可以这样使用:

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

@mplungjan在评论中提到的一件事,当文档。write执行它会擦除文档,所有脚本将被删除,所以你不应该使用document.write,而是使用一些替代方法,如@mplungjan张贴。

不能记录。在页面加载后写入。如果您这样做,页面将被擦除。

修改脚本以便稍后执行是很容易的。例如,将内容包装在函数中并更改任何文档。在里面写入字符串连接

(请显示代码)
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
}

您可以使用-

setTimeout(function() {
document.getElementsByTagName('body')[0].appendChild('<script>document.write("hello")</script>');
}, 5000);

基于注释-

作为一个建议,您不应该在文档加载之后添加这样的脚本。这是因为如果你使用'document.write('something')',它会删除文档中之前的内容,只写入'something'