At a Glance

  • Script tags have access to any element which appears before them in the HTML.
  • jQuery.ready / DOMContentLoaded occurs when all of the HTML is ready to interact with, but often before its been rendered to the screen.
  • The load event occurs when all of the HTML is loaded, and any subresources like images are loaded.
  • Use setTimeout to allow the page to be rendered before your code runs.

Deep Dive

The question of when your JavaScript should run comes down to ‘what do you need to interact with on the page?’.

Scripts have access to all of the elements on the page which are defined in the HTML file before the script tag. This means, if you put your script at the bottom of the <body> you know every element on the page will be ready to access through the DOM:

<html>
<body>
<div id="my-awesome-el"></div> <script>
document.querySelector('#my-awesome-el').innerHTML = new Date
</script>
</body>
</html>

This works just as well for external scripts (specified using the src attribute).

If, however, your script runs before your element is defined, you’re gonna have trouble:

<html>
<body>
<script>
document.querySelector('#my-awesome-el').innerHTML = new Date
/* ERROR! */
</script> <div id="my-awesome-el"></div>
</body>
</html>

There’s no technical difference between including your script in the <head> or <body>, all that matters is what is defined before the script tag in the HTML.

When All The HTML/DOM Is Ready

If you want to be able to access elements which occur later than your script tag, or you don’t know where users might be installing your script, you can wait for the entire HTML page to be parsed. This is done using either the DOMContentLoaded event, or if you use jQuery, jQuery.ready (sometimes referred to as $.ready, or just as $()).

<html>
<body>
<script>
window.addEventListener('DOMContentLoaded', function(){
document.querySelector('#my-awesome-el').innerHTML = new Date
});
</script> <div id="my-awesome-el"></div>
</body>
</html>

the same script using jQuery:

jQuery.ready(function(){
document.querySelector('#my-awesome-el').innerHTML = new Date
}); // OR $(function(){
document.querySelector('#my-awesome-el').innerHTML = new Date
});

It may seem a little odd that jQuery has so many syntaxes for doing the same thing, but that’s just a function of how common this requirement is.

Run When a Specific Element Has Loaded

DOMContentLoaded/jQuery.ready often occurs after the page has initially rendered. If you want to access an element the exact moment it’s parsed, before it’s rendered, you can use MutationObservers.

var MY_SELECTOR = ".blog-post" // Could be any selector

var observer = new MutationObserver(function(mutations){
for (var i=0; i < mutations.length; i++){
for (var j=0; j < mutations[i].addedNodes.length; j++){
// We're iterating through _all_ the elements as the parser parses them,
// deciding if they're the one we're looking for.
if (mutations[i].addedNodes[j].matches(MY_SELECTOR)){
alert("My Element Is Ready!"); // We found our element, we're done:
observer.disconnect();
};
}
}
}); observer.observe(document.documentElement, {
childList: true,
subtree: true
});

As this code is listening for when elements are rendered, the MutationObserver must be setup before the element you are looking for in the HTML. This commonly means setting it up in the <head> of the page.

For more things you can do with MutationObservers, take a look at our article on the topic.

Run When All Images And Other Resources Have Loaded

It’s less common, but sometimes you want your code to run when not just the HTML has been parsed, but all of the resources like images have been loaded. This is the time the page is fully rendered, meaning if you do add something to the page now, there will be a noticable ‘flash’ of the page before your new element appears.

window.addEventListener('load', function(){
// Everything has loaded!
});

Run When A Specific Image Has Loaded

If you are waiting on a specific resource, you can bind to the load event of just that element. This code requires access to the element itself, meaning it should appear after the element in the HTML source code, or happen inside a DOMContentLoaded or jQuery.ready handler function.

document.querySelector('img.my-image').addEventListener('load', function(){
// The image is ready!
});

Note that if the image fails to load for some reason, the load event will never fire. You can, however, bind to the error event in the same manner, allowing you to handle that case as well.

Run When My Current Changes Have Actually Rendered

Changes you make in your JavaScript code often don't actually render to the page immediately. In the interest of speed, the browser often waits until the next event loop cycle to render changes. Alternatively, it will wait until you request a property which will likely change after any pending renders happen.. If you need that rendering to occur, you can either wait for the next event loop tick;

setTimeout(function(){
// Everything will have rendered here
});

Or request a property which is known to trigger a render of anything pending:

el.offsetHeight // Trigger render

// el will have rendered here

The setTimeout trick in particular is also great if you’re waiting on other JavaScript code. When your setTimeout function is triggered, you know any other pending JavaScript on the page will have executed.

DOMContentLoaded vs jQuery.ready vs onload, How To Decide When Your Code Should Run的更多相关文章

  1. DOMContentLoaded和jquery的ready和window.onload的顺序

    document.addEventListener('DOMContentLoaded', function(){ alert(1) }); window.onload=function(){ ale ...

  2. window.onload、DOMContentLoaded和$(document).ready()

    <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="C ...

  3. jQuery Ready 与 Window onload 的区别(转)

    “我们都知道,很多时候,在页面加载完后都需要做一些相应的初始化动作.例如,运行某些js特效,设置表单等等.怎么知道页面加载完了呢?一 般情况下都是设置body标签的onload监听window的loa ...

  4. jQuery的document ready与 onload事件——你真的思考过吗?

    在进行实验和资料查询时,我遇到了几个关键问题: 1. window.onload到底是什么加载完触发? 2. body为什么会有onload事件? 3. 为什么是window.onload,而不是do ...

  5. 学习JQuery的$.Ready()与OnLoad事件比较

    $(document).Ready()方法 VS OnLoad事件 VS $(window).load()方法接触JQuery一般最先学到的是何时启动事件.在曾经很长一段时间里,在页面载入后引发的事件 ...

  6. jquery的$(document).ready()和onload的加载顺序

    最近在改一个嵌入在frame中的页面的时候,使用了jquery做效果,而页面本身也绑定了onload事件.改完后,Firefox下测试正常流畅,IE下就要等个十几秒jquery的效果才出现,黄花菜都凉 ...

  7. jquery ready和window onload区别

    window onload是指标签加载完成,并且标签资源加载完成: jquery ready是指标签加载完成,标签资源可能未加载完成 $(document).ready(function(){});= ...

  8. JavaScript window.onload 事件和 jQuery ready 函数有何不同?

    JavaScript window.onload 事件和 jQuery ready 函数之间的主要区别是,前者除了要等待 DOM 被创建还要等到包括大型图片.音频.视频在内的所有外部资源都完全加载.如 ...

  9. javascript jquery document.ready window.onload

    网易 博客 下载LOFTER客户端 注册登录  加关注 凡图的编程之路 2012年7月从一个编程新手的点点滴滴 首页 日志 LOFTER 相册 博友 关于我     日志       关于我 Holy ...

随机推荐

  1. 基于华为云CSE微服务接口兼容常见问题

    微服务接口兼容常见问题 在进行微服务持续迭代开发的过程中,由于新特性在不停的加入,一些过时的特性在不停的修改,接口兼容问题面临巨大的挑战,特别是在运行环境多版本共存(灰度发布)的情况下.本章节主要描述 ...

  2. mac mysql start ERROR! The server quit without updating PID file

    在mac下安装完mysql,启动时出现error: ERROR! The server quit without updating PID file (/usr/local/var/mysql/nal ...

  3. 洛谷 题解 P3161 【[CQOI2012]模拟工厂】

    本蒟蒻又双叒叕被爆踩辣! 题目链接 Solution: 这题又是一道贪心.. 数据范围: n<=15 ti<=100,000 gi<=10^9 mi<=10^9 这里就可以看到 ...

  4. shell执行数学运算

    整数: expr let $(()) $[] 浮点数: bc 1.使用expr ♦参与运算的成员和运算符之间必须有一个空格: ♦对于那些容易被shell错解的,在它们传入expr命令之前,需要使用sh ...

  5. 移动开发在路上-- IOS移动开发系列 多线程一

    类似于什么是进程什么是线程在这里我就不多浪费时间了(Google一下什么都有)! 废话不多说先上图,我相信大家都是喜欢看图的人,俗话说得好,求图求真相吗?虽然这里只有屌丝一个但是真相还是会有的... ...

  6. Java的值类型和引用类型

    一.问题描述 前几天因为一个需求出现了Bug.说高级点也挺高级,说白点也很简单.其实也就是一个很简单的Java基础入门时候的值类型和引用类型的区别.只是开发的时候由于自己的问题,导致小问题的出现.还好 ...

  7. HDU3870- intervals(差分约束)

    You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn. Write a program that: ...

  8. XCode项目配置

    此设置优先级在playersetting之上,如果为空或者格式不正确或者文件不存在将不会设置,请注意 一.设置面板 二.对应Xcode中设置 1.TeamID  登录苹果开发者网站,查看个人信息,就有 ...

  9. 自然语言处理(NLP) - 数学基础(1) - 排列组合

    正如我在<自然语言处理(NLP) - 数学基础(1) - 总述>一文中所提到的NLP所关联的概率论(Probability Theory)知识点是如此的多, 饭只能一口一口地吃了, 我们先 ...

  10. Python爬虫--喜马拉雅三国音频爬取

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:Botreechan  1.进入地址我们可以发现,页面有着非常整齐的目 ...