DOMContentLoaded vs jQuery.ready vs onload, How To Decide When Your Code Should Run

来源:https://www.cnblogs.com/pptu/archive/2019/12/04/11983686.html
-Advertisement-
Play Games

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 ...


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.


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 文中使用mysql5.7 版本實現多實例,埠為3306和3307。 1、多實例本質在一臺機器上開啟多個不同的mysql服務埠(3306,3307),運行多個mysql服務進程,這些服務進程通過不同的socket監聽不同的服務埠來提供各自的服務; 多個實例共用一套mysql安裝程式,配置文件可以 ...
  • 轉載請標明出處:https://www.cnblogs.com/tangZH/p/11985745.html 有些手機中,給TextView設置lineSpacingExtra後會出現最後一行的文字也出現lineSpacingExtra,不是某些版本才會,這跟機型有關。 可以用下麵這種方法解決: ...
  • 作為JavaScript開發人員,NPM是我們一直使用的東西,並且我們的腳本在終端上連續運行。 如果我們可以節省一些時間呢? 1、直接從npm打開文檔 如果我們可以直接使用npm跳轉到軟體包的文檔怎麼辦? 2、打開bug頁面 為了以防萬一,我們想在程式包上提交一個錯誤。 如果有這個包的作者的鏈接,將 ...
  • 在web開發時,可能經常會用到sessionstorage存儲數據,存儲單個字元串數據變數時並不困難 var str = 'This is a string'; sessionstorage.setItem('param',str); 獲取sessionstorage var item = sess ...
  • js Brendan(布蘭登) Eich 輕量級的編程語言(ECMAscript5或6), 是一種解釋性腳本語言(代碼不進行預編譯), 主要用來向HTML頁面添加交互行為, 目前是互聯網上最流行的腳本語言, 支持面向對象、命令式和聲明式(如函數式編程)風格, JavaScript,他和Python一 ...
  • 事故起源於一個魔鬼測試人員,某天做網站UI優化的時候,突然甩了一個問題給我 第二列的數據是可以跳轉至其他頁面的,但是,魔鬼測試的電腦上,一直都有一條數據是與其他的樣式不同,於是便甩了這個問題給我,我一瞅,喲呵,還真是,而且不管如何F5,Ctrl + F5,都不能改變它變黑的事實,一時間都不敢回消息了 ...
  • 從輸入URL到頁面載入發生了什麼? 最近在進行前端性能優化方面的一些工作,發現前端性能方面太廣,不知道如何下手。參考了許多文章,發現最終都會歸咎於一個非常經典的問題: 從輸入URL到頁面載入發生了什麼? 通過連接這個過程,然後針對性地對每個過程進行優化,最終實現的就是我們的前端性能優化。本篇文章主要 ...
  • 一、解決什麼問題 1、開發環境js、css不壓縮,可在瀏覽器選中代碼調試 2、開發環境運行http服務指向打包後的文件夾 3、babel輸出瀏覽器相容的js代碼 二、需要安裝的包 babel-loader:輸出瀏覽器相容的js代碼;命令:<!--?xml version="1.0" encoding ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...