当DOM“准备好”时运行JavaScript函数? [英] Run JavaScript function when the DOM is "ready"?

查看:92
本文介绍了当DOM“准备好”时运行JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个JavaScript上传脚本,该脚本表示在DOM准备就绪后立即运行初始化函数。我目前使用 body.onload 调用函数或者在定义函数后直接使用它。该函数在占位符div中构建一些HTML,作为文件上传工具。

I'm using a JavaScript upload script that says to run the initialize function as soon as the DOM is ready. I currently have it working just fine with either a call to the function with body.onload or directly after the function is defined. The function builds some HTML in a placeholder div that acts as the file uploader tool.

我的问题是这里的最佳做法是什么?既然它现在有效,那么为什么指令会在DOM准备好后立即运行init函数?我应该在占位符DIV之后直接添加< script>标记吗?

My question is what is the best practice here? Since it works for now, why would the instructions say to run the init function as soon as the DOM is ready? Should I be adding a <script> tag directly after the placeholder DIV for example?

推荐答案

最简单的解决方案是使用jQuery和它的 $(文件).ready(function(){....}); 函数。而不是 .... 你把自己的代码。

The easiest solution is using jQuery and its $(document).ready(function() { .... }); function. Instead of .... you put your own code.

注意它基本上做同样的事情@ Shadow2531建议,但也适用于不支持该事件的旧浏览器。

Note that it basically does the same thing @Shadow2531 suggested, but also works in old browsers not supporting that event.

这篇关于当DOM“准备好”时运行JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆