Relying on DOM readiness to invoke a function (instead of window.onload)

( From: http://www.javascriptkit.com/dhtmltutors/domready.shtml)
( Crazy implementation with pure javascript. Just in order to take place of " $(document).ready(function(){...});".
......

)

Relying on DOM readiness to invoke a function (instead of window.onload)

One of the most common event web developers check for before running their JavaScript is whether the page has completely loaded. For example:

window.οnlοad=function(){
  walkmydog()
}

This technique has become very popular as a way of defining our scripts in a central location without having to worry about the availability of the page content it seeks to manipulate. The bottom line is, when the page has fully loaded, whatever we want on the page has as well, ready to be molded. However, it's not without its flaws- waiting for the entire page to load literally means that, which can include slow loading images/iframes present on the page, and isn't always necessary. That's why Dean Edwards, JavaScript extraordinaire, came up with an alternate techniqueto detect page DOM readiness instead, which just means finding out when the document's DOM tree has fully initialized, versus the entire document and every object in it. A classic example is the insertion/ deletion of nodes via the DOM, which can in fact be done sooner rather than later, when the DOM has loaded versus the document itself (window.onload). In this tutorial, let me recap and perhaps refine a bit Dean Edward's technique for calling a function as soon as the document DOM is ready!

Relying <wbr>on <wbr>DOM <wbr>readiness <wbr>to <wbr>invoke <wbr>a <wbr>function <wbr>(instead <wbr>of <wbr>window.onload) Checking DOM readiness in Firefox and Opera 9+

In Firefox and Mozilla, checking for DOM readiness and executing a function when it's ready is simple, as a special "DOMContentLoaded" keyword is supported that can be used in place of an element when calling document.addEventListener():

if (document.addEventListener)
  document.addEventListener("DOMContentLoaded", walkmydog, false)

In this case the function walkmydog() will run as soon as the DOM for the document has fully initialized, which depending on the contents of your page can occur a lot sooner thanwindow.onload.

Relying <wbr>on <wbr>DOM <wbr>readiness <wbr>to <wbr>invoke <wbr>a <wbr>function <wbr>(instead <wbr>of <wbr>window.onload) Checking DOM readiness in Internet Explorer

In IE (includes IE7), there's no intrinsic way to detect DOM readiness. Dean Edwards came up with a roundabout solution instead, which relies on the behaviour of the defer attribute when added to an external JavaScript tag. In short this attribute causes IE to "defer" loading the referenced external JS file until the DOM has fully loaded, a behaviour that we can take advantage of here to accomplish what we want:

if (document.all && !window.opera){ //Crude test for IE //Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')
var contentloadtag=document.getElementByIdx_x_x("contentloadtag") contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete")
walkmydog() } }

As you can see, this technique centers around defining a "blank" external JavaScript tag with the "defer" attribute added. In IE, most elements support a "onreadystatechange" event that fires during each stage of the element's loading process, ending with "complete". So by probing theonreadystatechange event of our deferred blank JavaScript tag, we can in effect call the desired function when the DOM is ready.

Relying <wbr>on <wbr>DOM <wbr>readiness <wbr>to <wbr>invoke <wbr>a <wbr>function <wbr>(instead <wbr>of <wbr>window.onload) Putting it all together, plus a fall back plan

You just saw the two divergent techniques for detecting DOM readiness. It's time now to put the two halves together, but more importantly, implement a fall back mechanism for browsers that don't support any of the two "detect DOM readiness techniques" to default to using window.onloadinstead. With that said:

var alreadyrunflag=0 //flag to indicate whether target function has already been run
if (document.addEventListener) 
    document.addEventListener("DOMContentLoaded", function(){
        alreadyrunflag=1; 
        walkmydog()
    }, false) 
else if (document.all && !window.opera){ 
    document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>') ;
    var contentloadtag=document.getElementByIdx_x_x("contentloadtag");    
    contentloadtag.onreadystatechange=function(){ 
        if (this.readyState=="complete"){ 
            alreadyrunflag=1; 
            walkmydog() 
        } 
    } 
} 
window.οnlοad=function(){ setTimeout("if (!alreadyrunflag) walkmydog()", 0) }

Note the code in red- this is our fallback mechanism that shall account for the scenario in which the target function wasn't run at the DOM ready stage for any reason, and run it via the traditional window.onload event instead. With it in place, no browser should fall through the cracks at the end of the day. Two things I should point out with this scheme that makes it work:

  • A global flag "alreadyrunflag" is defined to let the fallback code know whether it should run the target function via window.onload. If the flag evaluates to true, it means the target function has already been run at the DOM readiness stage (which proceeds window.onload).

  •  In IE and for very basic pages that contain just a few lines of text, there is the possibility that window.onload could fire at the same time the readyState property of the external JavaScript tag evaluates to "complete", instead of the former always following the later . In such a unique case, the flag alreadyrunflag won't evaluate to true in time for our fall back function to know that the target function has already been run in IE, and will run it again. This problem can easily be fixed by embedding a setTimeout() within window.onload, ensuring the code attached to this event will in fact always be the very last thing run on the page.

And there you have it- a way to launch functions as soon as the DOM is ready and not leave non capable browsers in the dust. Using the exact same technique, the below example shows launching two functions this time around, the later with a parameter:

var alreadyrunflag=0 //flag to indicate whether target function has already been run if (document.addEventListener) document.addEventListener("DOMContentLoaded", function(){alreadyrunflag=1; walkmydog(); feedcat('grapes')}, false) else if (document.all && !window.opera){ document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>') var contentloadtag=document.getElementByIdx_x_x("contentloadtag") contentloadtag.onreadystatechange=function(){ if (this.readyState=="complete"){ alreadyrunflag=1 walkmydog() feedcat('grapes') } } } window.οnlοad=function(){ setTimeout("if (!alreadyrunflag){walkmydog(); feedcat('grapes')}", 0) }
Relying <wbr>on <wbr>DOM <wbr>readiness <wbr>to <wbr>invoke <wbr>a <wbr>function <wbr>(instead <wbr>of <wbr>window.onload) In conclusion, and checking for  DOM readiness in Safari

The advantage of running a function as soon as the DOM is ready versus window.onload materializes on pages that are heavy on mages or iframe tags. Ultimately you have the weigh the benefits versus the additional code and work needed to implement such a technique. Before I conclude this tutorial, there's an elephant in the room I've been ignoring until now. Apparently in Safari it's also possible to check for DOM readiness, and Dean Edward referred to John Resig in coming up with a way to do so in that browser:

if(/Safari/i.test(navigator.userAgent)){ //Test for Safari var _timer=setInterval(function(){ if(/loaded|complete/.test(document.readyState)){ clearInterval(_timer) walkmydog() // call target function }}, 10) }

It's the obsessive DOM readiness checker! In Safari, apparently, what you need to do is manually probe the document.readyState property at fast paced intervals to see when it returns either "loaded" or "completed" (usually the former proceeds the later, but to be safe, check both). That's when you know the DOM is ready and to fire your desired function. Personally I'm not keen on implementing it, as this is where the technique crosses the line and becomes a burden in my opinion considering the small group it benefits. And yes we're all entitled to our opinions!

 

【LAMMPS学习】八、基础知识(2.1)2D模拟 此部分描述了如何使用 LAMMPS 为用户和开发人员执行各种任务。术语表页面还列出了 MD 术语,以及相应 LAMMPS 手册页的链接。LAMMPS 源代码分发的examples目录中包含的示例输入脚本以及示例脚本页面上突出显示的示例输入脚本还展示了如何设置和运行各种模拟。 阅读详情

相关推荐

保姆级教程:用NovAtel Inertial Explorer 8.7搞定GNSS/INS紧组合后处理(附避坑指南)

本文提供NovAtel Inertial Explorer 8.7的GNSS/INS紧组合后处理全流程教程,涵盖环境准备、数据转换、基站坐标解算及紧组合处理等关键步骤。特别针对零基础用户,分享实用技巧和常见陷阱,帮助高效完成高精度组合导航数据处理,适用于测绘、自动驾驶等领域。

weixin_42614269的博客 291

【转】DNS协议报文(RFC1035)

(转自:http://hi.baidu.com/wzypunk/blog/item/1fb46d26fb4130fcd6cae22e.html)DNS协议报文(RFC1035) 2010-10-16 17:19 一、域名和资源记录的定义 1、Name space definitions2、资源记录定义(RR definitions)    2.1 格式         后面分析报文...

837

gRPC之gRPC开发流程与入门案例

gRPC之gRPC开发流程与入门案例

YIYIYI 3765

Table单元格td的position:relative的兼容性

( From:  http://www.itref.cn/a/css/2010/0706/70.html)问题描述: 默认情况下,table的单元格td的display为table-cell,在IE给td设置position:relative,然后给它包含的一个容器使用position:absolute进行定位是有效的,但在FF下却不可以。但是在IE下,position:absolute的容器的...

735

从ADRV9002到ADRV9003:手把手教你移植FPGA驱动,避开那些官方没说的坑

本文详细介绍了从ADRV9002到ADRV9003的FPGA驱动移植实战指南,重点解析了两者在硬件架构上的关键差异,如通道配置和DPD功能的移除。通过提供完整的移植步骤、调试技巧和性能优化建议,帮助工程师避开官方文档未提及的常见陷阱,实现高效驱动开发。

weixin_28738397的博客 180

MLIR驱动的CUDA契约重构:2026底层计算范式跃迁

CUDA已从运行时库演进为编译器中心化契约体系,其核心不再是API调用优化,而是通过MLIR等高层中间表示精准声明计算意图与硬件约束。这一转变源于GPU架构复杂度激增与AI/科学计算对确定性SLA的刚性需求——需在跨千卡训练、亚毫秒推理、异构协同等场景中实现资源可声明、可验证、可协商。MLIR作为‘契约语言’,支持linalg语义建模、硬件能力(HCDL)描述、async跨设备调度及SASS级编译优化,使开发者角色从调优工程师升级为契约架构师。本文聚焦CUDA 12.8+时代下,以MLIR为枢纽的计算契约重

weixin_29048309的博客 141

【转】Calling Cross Domain Web Services in AJAX

(From: http://www.simple-talk.com/dotnet/asp.net/calling-cross-domain-web-services-in-ajax/)( Joson:  Here is the most excellent article about cross-domain http request, so far as I searched.  And  ...

459

均匀分布产生高斯分布

均匀分布产生高斯分布 文章目录均匀分布产生高斯分布简介方法和证明代码效果引用 简介 方法和证明 代码 效果 引用

gy_Rick的博客 5323

HTTP Status Code

(From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)part of Hypertext Transfer Protocol -- HTTP/1.1RFC 2616 Fielding, et al. 10 Status Code Definitions Each Status-Code is described below...

415

D触发器(D Flip-Flop)与D锁存器(D Latch)

在解释这个练习题之前,我们先来简单回顾一下D触发器(D flip-flop)和D锁存器(D latch)的概念,以及它们在数字电路中的作用。这将帮助我们理解所提到的练习。

weixin_65190179的博客 9201

SAP 角色继承、派生

角色继承、派生 继承:是指两个角色Role形成母子关系。子角色的所有菜单、授权都源于母角色,并与母角色保持一致。母角色与子角色是1对多的关系。 继承关系:新建子角色继承母角色中的事务(后续通过复制,将母角色授权数据复制至子角色) 派生概念:将母角色中的授权数据派生至子角色中。 业务场景:方便批量修改子角色权限。若有继承关系,只需要修改母角色,然后通过母角色派生功能,从而批量修改子角色授权数...

willieyuan的博客 1万+

【转】DNS报文格式

(转自:http://hi.baidu.com/hcq11/blog/item/5e3a1bed2ef1ced8b21cb179.html/cmtid/3d8f1b9074f6cb80a877a4f6) 总结:DNS报文格式 2010-04-08 10:13 DNS报文格式(借个图贴过来):     说明一下:并不是所有DNS报文都有以上各个部分的。图中标示的“12字节”...

324

PCL体素滤波器【2026最新版】

PCL实现的VoxelGrid类和ApproximateVoxelGrid体素滤波,详细记录。博客长期更新,本文最近一次更新时间为:2026年3月14日。

点云侠的博客 39万+

HTTP multipart/form-data 上传方式说明

  ( From: http://home.meegoq.com/home-space-do-blog-uid-17-id-81.html ) HTTP multipart/form-data 上传方式说明 已有 123 次阅读 2010-12-1 11:13 |个人分类:网络学习|关键词:HTTP multipart http上传文件方面的功能使用的协议是rfc1867 (ht...

292

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

(转)UPNP协议细节

(From: http://www.cnblogs.com/semo/archive/2008/07/21/1247950.html)UPNP的全称是 Universal plug-and-play( 通用即插即用).UPnP 是针对智能家电、无线设备以及各种外观尺寸的个人电脑的普遍对等(peer-to-peer)网络连接而设计的一种架构。它旨在为家庭、小型企业、公共场 所中或连接到互联网的ad-...

237

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

[转] HTTP multipart/form-data 上传方式说明

( From: http://home.meegoq.com/home-space-do-blog-uid-17-id-81.html ) HTTP multipart/form-data 上传方式说明 已有 123 次阅读 2010-12-1 11:13 |个人分类:网络学习|关键词:HTTP multipart http上传文件方面的功能使用的协议是rfc1867 (http...

235

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

HTTP Request

HTTP Request Published in: JavaScript  Generic global code for managing XMLHttpRequest objects. Expand | Embed | Plain Text // ---------------------------------------- ...

218

a lib: jXHR (JSON-P XHR)

http://mulletxhr.com/

218

【转】Webcam Manipulation with Javascript

( From:http://blog.trumpton.org.uk/2009/02/webcam-manipulation-with-javascript.html )I purchased an IcamView web server, and megapixel webcam, which I have waterproofed, and placed in the garden.The I...

217

Single Sign-On

Single Sign-On Single sign-on (SSO) is mechanism whereby a single action of user authentication and authorization can permit a user to access all computers and systems where he has access permission,...

212

【转】DNS协议及应用

(转自http://jwx.zgz.cn/cl/7.41.htm) 7.4.1 DNS协议及应用         DNS属于应用层的协议,DNS提供了将人类易于理解的主机名或域名转换为计算机或网络可识别的数字地址的机制,从而使得互连网的广泛应用成为可能。    一、 DNS涉及的基本概念    (1)域名及顶级域    1)域名    域名(Domain Nam...

212

环信 GitHub 仓库索引——全部SDK、UIKit 与 CallKit、Demo 与集成示例

本文档汇总环信官方及社区GitHub仓库,涵盖多端IM SDK、UIKit、CallKit组件及完整Demo,支持iOS、Android、Flutter、React Native、HarmonyOS等平台,提供快速集成与开发参考。

huan132456765的博客 213

JS 打印空白页:网页打印控件 iframe 时序排查与修复

从整页空白复现出发,定位 iframe onload 与 document.write 的时序竞争。本文结合具体场景讲清做法、常见问题与可复用的实现思路。

一天拉了7遍的博客 137

基于Docker Compose 部署RuoYi-Vue 前后端分离后台管理系统

RuoYi-Vue是前后端分离的后台管理系统若依是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。是一个 Java EE 企业级快速开发平台,基于经典技术组合(Spring Boot、Spring Security、MyBatis、Jwt、Vue),内置模块如:部门管理、角色用户、菜单及按钮授权、数据权限、系统参数、日志管理、通知公告、代码生成等。在线定时任务配置,支持集群,支持多数据源,支持分布式事务等。

一直在努力学习的菜鸟 216

靓车汽车销售网站设计与实现:SpringBoot 汽车销售 203 个接口,附论文与运行截图

# 靓车汽车销售网站设计与实现:SpringBoot 汽车销售 203 个接口,附论文与运行截图 ## 目录 - [一、你是不是也这样](#一你是不是也这样) - [二、这套是什么](#二这套是什么) - [三、对你具体有什么用](#三对你具体有什么用) - [四、怎么跑起来](#四怎么跑起来) - [五、里面有什么](#五里面有什么) --- ## 一、你是不是也这样 选题报到「销售网

面朝大海 352

副队长 Vue3 教程(19)--组件 props 父传子

本文讲解Vue组件通信中的props机制,实现父组件向子组件传递数据。通过defineProps对象写法进行类型校验、必填判断与默认值设置,推荐用于正式项目。重点强调单向数据流原则:子组件不可直接修改props,避免数据污染。结合待办清单案例,演示如何循环渲染多条待办项,并指出常见错误如直接修改props、默认值未用函数返回等。最后提示后续学习defineEmits实现子传父。

编程副队长 314
上一篇: 【转】Calling Cross Domain Web Services in AJAX
下一篇: 【转】HTTP协议报文格式
excpp
博客等级 码龄15年 0粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址