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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...