Get the App
SLTechnology News&Howtos  ›  Development  › 

JS is compatible with all browsers how to use the DOMContentLoaded event

Shulou Source: shulou.com Published: 2022-06-03 19:12:46 10月06日 Update

Editor to share with you how to use DOMContentLoaded events of JS compatible with all browsers, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's learn about it together.

Introduction to the implementation process:

In standard browsers, our requirements can be achieved by using DOMContentLoaded events, and registering event handlers is extremely simple.

The code is as follows:

AddEventListener ('DOMContentLoaded',fn,false)

However, browsers below IE8 and IE8 do not support DOMContentLoaded events, so you need to find another way to solve this problem.

Many friends may think that judging whether the dom structure is loaded according to whether the document.readyState status of the _ document.onreadystatechange event is equal to complete, but the task cannot be completed after testing. If the page uses iframe to introduce sub-pages, there will be problems.

Solutions are as follows:

The doScroll method peculiar to the lower version of IE browser. Calling this method will report an error when the dom structure is not loaded, so you can call this method constantly through the timer function and combine the try catch statement to achieve the judgment function. The code is as follows:

EventQueue = []; isReady = false;isBind = false;function domReady (fn) {if (isReady) {fn.call (window);} else {eventQueue.push (fn);}; bindReady ();}; function bindReady () {if (isReady) return; if (isBind) return; isBind=true; if (window.addEventListener) {document.addEventListener ('DOMContentLoaded',execFn,false);} else if (window.attachEvent) {doScroll ();};} Function doScroll () {try {document.documentElement.doScroll ('left');} catch (error) {return setTimeout (doScroll,20);}; execFn ();}; function execFn () {if (! isReady) {isReady=true; for (var index=0;i)

Tags: Function event browser browser code array processing variable article structure continuity content initial value function timer effect method standard this method process Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Huawei Docker Shulou Information OPPO Reno