`

How Javascript Loading Works - DOMContentLoaded and OnLoad

    博客分类:
 
阅读更多

Fonts by Typekit

How Javascript Loading Works - DOMContentLoaded and OnLoad

14 June 2011

There are actually three different windows of time during a web request in which we can load and execute javascript. These windows are delineated by the DOMContentLoaded event and the OnLoad event. We can load our scripts before DOMContentLoaded, after DOMContentLoad, and after OnLoad. But before I dig into the details of how this is done, what the heck are these two events and when are they actually triggered?

The Events

The DOMContentLoaded event is triggered when the page's Document Object Model (DOM) is ready.  What this means is that the API for interacting with the content, style and structure of a page is ready to receive requests from your code. In general this means that the text, css and html are ready - but it's not quite that simple. Depending on the browser, HTML version, and where the stylesheet tags are relative to the script tags, the CSS might not be done rendering by the time this event fires. Fortunately there is a safe and performant way to ensure that the CSS is loaded first. It's as simple as placing your external stylesheets in the header and your external javascripts in the footer. This approach forces the javascript to execute only after the external stylesheets and HTML body have been loaded. Basically, this means that if you are placing stylesheets in the header and javascripts in the footer, your DOM will load all content, structure, and style before the DOMContentLoaded event is fired. That's a good thing!

The OnLoad event is triggered when the entire page has loaded. This is moment when the globe or loader in your browser's title bar stops spinning. At this point all scripts and stylesheets have finished loading and have been executed, and all images have been downloaded and displayed.

Loading Javascript

So how do we hook into each of these events; and more importantly, when should we use each? To examine the different hooks, let's have a look at this simple HTML page and the output that it produces.

<!DOCTYPE html>
<body>
  <script src="jquery.min.js"></script>
  <script src="external.js"></script>
  <script type='text/javascript'>
    //<![CDATA[
      $.getScript('ajax.js');
      $(document).ready(function(){
        console.log('DOM Loaded (DOMContentLoaded)');
        $('head').append('<script src="dom.js"></script>');
        $.getScript('dom_ajax.js');
      });
      $(window).load(function(){
        console.log('Page Loaded (OnLoad)');
        $.getScript('page_ajax.js');
      });
    //]]>
  </script>
</body>

If we examine the javascript console we can see the list of events play out like this:

external.js Loaded and Executed
DOM Loaded (DOMContentLoaded)
dom.js Loaded and Executed
Page Loaded (OnLoad)
ajax.js Loaded and Executed
dom_ajax.js Loaded and Executed
page_ajax.js Loaded and Executed

This console output implicates the three windows of javascript loading:

  • External javascript (external.js) is loaded before DOMContentLoaded.
  • External javascript inserted into HTML during the DOMContentLoaded callback (dom.js) is loaded before OnLoad.
  • AJAX requests do not delay DOMContentLoaded or OnLoad, regardless of when they are initiated (ajax.js, dom_ajax.js and page_ajax.js).

Let's take a look at each of these windows and see which one best suits our needs.

Before DOMContentLoaded

First, notice that both inline javascript and external javascript (external.js) is loaded and executed immediately, regardless of the DOM being ready or the page having been loaded.  This may seem obvious, but it is necessary to execute this code before DOMContentLoaded so that we can actually hook into the event. The best way to think of this javascript is as a setup. You shouldn't be manipulating the DOM yet, since it isn't ready - you should be setting up your callbacks and then getting out of the way so the rest of the page can load quickly.

After DOMContentLoaded

These scritpts (dom.js) are executed once the DOM is ready to be manipulated. This where you want to put any code that actually changes the page visually as this is the earliest point at which DOM manipulation is possible, and it will be executed before the page is displayed. This is a good thing because we don't want the page elements jumping around and changing style after they are visible to the user.

After OnLoad

These scripts (ajax requests and anything in the window.load callback) are executed after the page has completed loading and the user can view the entire document. This is a great place to load long-running scripts and scripts that don't visually alter the page.  Some examples of this include analytics and reporting libraries and code or data that might be used later and can be pre-fetched for the user.  Google maps loads all of its map tiles using AJAX so that the page load is not halted.

Takeaway

Try to keep this page load process in mind when writing your javascript code. Simple placement of your code can lead to large gains in overall perceived page load time.  I'm hoping this blog post clarifies the basic page load events and allows you to beter determine how and where javascript should be loaded in your own application. If you have any questions or examples of these methods in use, please leave a comment.

Related Posts

<iframe id="dsq-2" style="margin: 0px; padding: 0px; width: 660.2833251953125px; border-style: none !important; overflow: hidden !important; height: 1152px !important;" src="http://disqus.com/embed/comments/?disqus_version=8f9aa1a0&amp;base=default&amp;f=ablogaboutcode&amp;t_u=http%3A%2F%2Fablogaboutcode.com%2F2011%2F06%2F14%2Fhow-javascript-loading-works-domcontentloaded-and-onload%2F&amp;t_d=How%20Javascript%20Loading%20Works%20-%20DOMContentLoaded%20and%20OnLoad&amp;t_t=How%20Javascript%20Loading%20Works%20-%20DOMContentLoaded%20and%20OnLoad&amp;s_o=default#2" frameborder="0" scrolling="no" width="100%" data-disqus-uid="2"></iframe>
分享到:
评论

相关推荐

    loading图标-gif-HTML-代码

    在网页设计中,加载图标(loading icon)是一个重要的元素,特别是在内容加载期间,它能提供用户反馈,告知他们页面正在加载。"loading图标-gif-HTML-代码"这个项目涉及了如何在HTML页面中实现一个动态的加载图标,...

    javascript经典特效---从左飞入的文字.rar

    可以使用`window.onload`或`DOMContentLoaded`事件来确保在所有资源加载完成后执行动画代码。 此外,为了提高代码的可维护性和复用性,可以将动画逻辑封装成一个函数,甚至是一个自定义的JavaScript组件。这需要...

    javascript经典特效---图片随意移动.rar

    可以使用`window.onload`或`DOMContentLoaded`事件来确保在页面加载完成后执行JavaScript代码: ```javascript document.addEventListener('DOMContentLoaded', function() { var img = document.getElementById('...

    javascript经典特效---滚动初始状态为停.rar

    这可能涉及到JavaScript中的事件监听,如`DOMContentLoaded`事件,确保页面内容加载完毕后才执行滚动函数;或者可以设置一个按钮,当用户点击按钮时启动滚动。 实现滚动特效还可能用到定时器(`setInterval`或`...

    javascript经典特效---打开页面的等待(三).rar

    考虑到性能和浏览器兼容性,可以使用`DOMContentLoaded`事件替代`window.onload`,它在DOM解析完成时触发,不等待资源加载。如果需要兼容旧版浏览器,可以同时监听这两个事件。 7. **异步加载** 当页面有大量异步...

    javascript经典特效---title栏文字出现.rar

    5. **事件监听**:如果希望在特定的用户交互(如页面加载完成后)开始这个动画,可以使用`window.onload`或`DOMContentLoaded`事件来监听页面加载状态。 6. **兼容性考虑**:由于不同的浏览器可能对某些JavaScript...

    javascript经典特效---窗口打开后的移动.rar

    这可以结合`window.onload`事件或`DOMContentLoaded`事件来完成。例如: ```javascript window.onload = function() { // 窗口初始位置 var x = 0, y = 0; // 每隔一段时间(如100毫秒)移动窗口 setInterval...

    javascript经典特效---奇特的文字显示信息.rar

    例如,使用`requestAnimationFrame`来实现平滑的动画效果,或者通过事件监听(如`window.onload`或`DOMContentLoaded`)确保脚本在页面加载完成后执行。 总的来说,这个压缩包提供了一个学习和实践JavaScript动态...

    javascript经典特效---文字从背景中来.rar

    3. **JavaScript事件**:事件监听器如`DOMContentLoaded`或`window.onload`确保在所有资源加载完成后执行JavaScript代码。 4. **DOM操作**:JavaScript通过`document.getElementById`或`querySelector`等方法找到...

    javascript经典特效---打开页面特效(一).rar

    3. **事件监听**:为了在页面加载时触发特效,开发者需要监听“DOMContentLoaded”或“window.onload”事件,确保在所有资源加载完毕后执行特效代码。 4. **时间函数和定时器**:`setTimeout`和`setInterval`是常用...

    javascript经典特效---title显示链接路径.rar

    另外,也可以使用`window.onload`或`DOMContentLoaded`事件来确保在页面内容完全加载后再执行这段代码。 总结起来,"javascript经典特效---title显示链接路径"是一个利用JavaScript改变HTML元素属性的实例,通过...

    javascript经典特效---打开页面特效(五).rar

    这可以通过监听`window.onload`事件来触发动画,或者使用`DOMContentLoaded`事件在DOM结构加载完成后立即执行特效。 2. **元素位置变换**:JavaScript可以改变HTML元素的位置和大小,通过设置`style`属性,可以实时...

    javascript经典特效---上下跳动的宣传图片.rar

    在JavaScript编程领域中,创建动态效果是提升用户体验的重要手段之一。在这个上下跳动的宣传图片示例中,我们将深入探讨如何利用JavaScript实现这样的动画效果。首先,我们需要理解HTML、CSS和JavaScript之间的协作...

    javascript经典特效---文字飞舞欢迎.rar

    【标题】"JavaScript经典特效---文字飞舞欢迎"是一个典型的网页动态效果,它利用JavaScript语言来实现文字在页面上以动态、随机的方式呈现,给访问者带来视觉上的吸引力。这种特效常见于网站的欢迎页或者作为吸引...

    javascript经典特效---按钮显示特殊内容.rar

    例如,使用`DOMContentLoaded`事件确保在文档加载完成后才执行JavaScript代码,避免阻塞页面渲染。另外,对于无障碍性(accessibility),确保按钮有明确的`aria-label`或`title`属性,以便屏幕阅读器的用户理解其...

    javascript经典特效---文字缩放出现.rar

    在JavaScript的世界里,实现动态效果是一项常见的任务,而“文字缩放出现”是网页交互设计中的一种经典特效。这个特效可以提升用户体验,使网站或应用更加生动有趣。在这个压缩包"javascript经典特效---文字缩放出现...

    javascript经典特效---查找页面中的字符.rar

    JavaScript是一种广泛应用于网页和网络应用的编程语言,尤其在实现客户端动态效果和交互性方面具有重要作用。本资源“javascript经典特效---查找页面中的字符.rar”显然聚焦于如何使用JavaScript来查找网页中的特定...

    javascript经典特效---树形菜单(一).rar

    在JavaScript的世界里,树形菜单是一种常见的用户界面元素,它以层次结构展示数据,通常用于网站导航、文件系统浏览或数据库记录的展示。本压缩包文件"javascript经典特效---树形菜单(一).rar"主要关注如何使用...

    javascript经典特效---招牌文字特效.rar

    这里可能会使用到`window.onload`或`DOMContentLoaded`事件来确保在页面完全加载后执行脚本。通过`document.getElementById`或`document.querySelector`选择特定元素,然后使用`style`对象改变元素的样式,如修改`...

    javascript经典特效---时间跳动器.rar

    例如,我们可以通过window.onload事件确保在页面加载完成后才开始显示时间跳动器,或者使用DOMContentLoaded事件等待DOM结构加载完毕。 DOM操作是JavaScript与HTML进行交互的方式。在时间跳动器中,我们需要找到...

Global site tag (gtag.js) - Google Analytics