Onload

readyState

В заключение
занятия отметим свойство

document.readyState

которое в момент
загрузки HTML-документа принимает
следующие значения:

  • «loading»
    – документ в процессе загрузки;

  • «interactive»
    – документ был полностью прочитан (парсинг документа завершен);

  • «complete»
    – документ был полностью прочитан и все ресурсы (изображения, стили и т.п.)
    тоже загружены.

В ряде случаев
это свойство бывает весьма полезно. Например, мы вызываем функцию, но не
уверены, что DOM-дерево
полностью построено. Поэтому, делаем такую проверку:

removeImage();
function removeImage() {
     if(document.readyState == "loading") {
          console.log("документ грузится, вешаем обработчик");
          document.addEventListener("DOMContentLoaded", removeImage);
     }
     else {
          console.log("удаляем изображение");
          document.body.remove(image);
     }
}

По аналогии
могут быть обработаны и остальные свойства.

Для полноты картины
пару слов о событии readystatechange, которое появилось до событий

DOMContentLoaded, load, unload, beforeunload

и в старых версиях
JavaScript процесс
загрузки документа контролировался через него. Например, так:

document.addEventListener('readystatechange', function() {
         console.log(document.readyState);
});

Теперь при
обновлении страницы мы можем увидеть изменение состояний свойства document.readyState в процессе
загрузки. Однако такой механизм отслеживания ушел в прошлое и сейчас уже нет смысла
о нем подробно говорить.

Итак, на этом
занятии мы с вами рассмотрели события

DOMContentLoaded,
load, unload, beforeunload

и поговорили о свойстве

document.readyState

которое
дополняет работу с этими событиями.

Видео по теме

JavaScipt (DOM) #1: объектная модель документа DOM и BOM

JavaScipt (DOM) #2: навигация по DOM — parentNode, nextSibling, previousSibling, chidNodes

JavaScipt (DOM) #3: методы поиска элементов в DOM: querySelector, querySelectorAll, getElementById

JavaScipt (DOM) #4: свойства DOM-узлов: nodeName, innerHTML, outerHTML, data, textContent, hidden

JavaScipt (DOM) #5: работа с нестандартными свойствами DOM-элементов: getAttribute, setAttribute, dataset

JavaScipt (DOM) #6: создание и добавление элементов DOM createElement, append, remove, insertAdjacentHTML

JavaScipt (DOM) #7: управление стилями — className, style, classList, getComputedStyle

JavaScipt (DOM) #8: метрики — clientWidth, scrollTop, scrollHeight, offsetLeft, offsetTop, clientLeft

JavaScipt (DOM) #9: HTML-документ: размеры (clientWidth, innerWidth), положение (pageYOffset, scrollBy)

JavaScipt (DOM) #10: расположение элементов — fixed, absolute, getBoundingClientRect, elementFromPoint

JavaScipt (DOM) #11: обработчики событий: onclick, addEventListener, removeEventListener, event

JavaScipt (DOM) #12: погружение и всплытие событий: stopPropagation, stopImmediatePropagation, eventPhase

JavaScipt (DOM) #13: делегирование событий, отмена действия браузера по умолчанию — preventDefault

JavaScipt (DOM) #14: события мыши mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter

JavaScipt (DOM) #15: события клавиатуры keydown, keyup, событие скроллинга scroll

JavaScipt (DOM) #16: навигация и обработка элементов форм (form) — document.forms, form.elements

JavaScipt (DOM) #17: фокусировка — focus, blur, focusin, focusout, tabindex, activeElement

JavaScipt (DOM) #18: события change, input, cut, copy, paste, submit элементов input и select

JavaScipt (DOM) #19: события при загрузке — DOMContentLoaded, load, unload, beforeunload, readyState

JavaScipt (DOM) #20: события load, error; атрибуты async, defer тега script

JavaScipt (DOM) #21: пример предзагрузки изображений с помощью javascript

JavaScipt (DOM) #22: пример создания начала игры арканоид

More Examples

Example

Using onload on an <img> element. Alert «Image is loaded» immediately after
an image has been loaded:

<img src=»w3javascript.gif» onload=»loadImage()» width=»100″ height=»132″><script>function loadImage() {  alert(«Image is loaded»);}
</script>

Example

Using the onload event to deal with cookies:

<body onload=»checkCookies()»><script>
function checkCookies() {  var text = «»;  if (navigator.cookieEnabled == true) {    text = «Cookies are enabled.»;  } else {     text = «Cookies are not enabled.»;
  }  document.getElementById(«demo»).innerHTML = text;}</script>

❮ DOM Events
❮ Event Object

ReadyState¶

The document.readyState property informs about the current loading state.

Three possible values can be distinguished:

  • "loading": the state of loading the document.
  • «interactive»"interactive": the document is completely read.
  • "complete": the document is completely read, and all the resources are loaded.

So, you can check document.readyState and set up a handler, executing the code immediately when it’s ready.

Here is an example of using document.readyState:

You can also use the readystatechange event, which gets activated when the state changes. So, all the state can be printed as follows:

Try it Yourself »

So, this event is an alternative way of tracking the document loading state. But, nowadays, it’s not used often.

The complete events flow will look like this:

Try it Yourself »

The example above includes <iframe>, <img>, as well as handlers for logging events.

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Summary¶

Let’s sum up when the page load events trigger and what they can be useful for.

In brief, the page load events are the following:

  • The DOMContentLoaded event happens on the document when the DOM is ready. So, JavaScript can be applied to elements at this stage.
  • The load event on the window occurs once the page and all the resources are loaded. As a rule, it’s rarely used.
  • The beforeunload event is activated on the window when the user intends to leave the page. While canceling the event, the browser asks whether the user really wishes to leave.
  • The unload event triggers once the user is leaving.
  • And, finally, the document.readyState is the current state of the document. The changes can be tracked in the readystatechange in the following states: (the document is in the loading state), interactive ( the document is parsed), complete (the document and the resources are load).

Window.onunload¶

The unload event triggers on the window when a visitor leaves the page. You can do there something that doesn’t include a delay (for example, closing related popup window). Sending analytics is considered a notable exception.

Imagine, you want to gather data about how the page is used: scrolls, mouse clicks, and so on. As a rule, the unload event is when the user leaves the page, and you want to save the data on the server. A unique navigator.sendBeacon(url, data) method exists for such needs. It can send the data to the background. Also, there is no delay in the transition to another page still performing sendBeacon.

Here is an example of using sendBeacon:

So, in the example above:

  1. The request is forwarded as POST.
  2. It is possible to send not only a string but also forms and other formats.
  3. There is a data limit: 64kb.

Once the sendBeacon request is over, the browser has probably left the document. Therefore, there is no way of getting server response (for analytics, it’s usually empty).

Also, you can use keepalive to perform “after-page-left” requests in the fetch method for generic network requests.

For canceling the transition to another page, you can use another event: onbeforeunload.

More Examples

Example

Using onload on an <img> element. Alert «Image is loaded» immediately after
an image has been loaded:

<img src=»w3html.gif» onload=»loadImage()» width=»100″ height=»132″><script>function loadImage() {    alert(«Image is loaded»);}
</script>

Example

Using the onload event to deal with cookies (using «advanced» javascript):

<body onload=»checkCookies()»><p id=»demo»></p><script>
function checkCookies() {    var text = «»;    if (navigator.cookieEnabled == true) {        text = «Cookies are enabled.»;    } else {        text = «Cookies are not enabled.»;    }
   
document.getElementById(«demo»).innerHTML = text;}</script>

DOMContentLoaded¶

This event occurs on the document object.

The addEventListener should be used to catch it, like this:

Here is an extensive example of using addEventListener:

Try it Yourself »

In the example above, the DOMContentLoaded runs once the document is loaded. So, it is capable of seeing all the elements, including <img>.

But, note that it never waits for the image to load. Hence, the alert will show zero sizes.

The DOMContentLoaded event looks very simple at first sight. But, the event comes when the DOM tree is ready.

However, few peculiarities exist that we are going to cover further.

DOMContentLoaded and Scripts

Once the document processes an HTML-document and passes through a <script> tag, it should execute before continuing to set up the DOM. It’s like a precaution because scripts might want to modify the DOM, and, moreover, document.write into it. Therefore, the DOMContentLoaded should wait.

So, the DOMContentLoaded event occurs after scripts like this:

Try it Yourself »

As you can notice from the example above, first comes “Library loaded…” , only then “DOM ready”.

Please, note that there are exceptions to this rule. That is to say, the scripts with async attribute never block DOMContentLoaded. The scripts that are created dynamically using document.createElement('script') and added to the webpage after, don’t block this event, either.

DOMContentLoaded and Styles

The DOM is not affected by external style sheets, so DOMContentLoaded doesn’t wait for them.

But there is a drawback here. If there is a script after the style, then the script shall wait till the stylesheet is loading, like this:

Try it Yourself »

That happens because the script might want to get coordinates or other style-dependant properties. So, it should wait for the style to load. As though DOMContentLoaded waits for the scripts, it will wait for the styles before them, too.

Built-in Browser Autofill

Chrome, Opera and Firefox can autofill forms on DOMContentLoaded. For example, if there is a page form with a login and password, and the browser remembered the values, then it might try to autofill them on DOMContentLoaded (it should be approved by the user).

Moreover, if DOMContentLoaded is suspended by the long-load scripts, the autofill should also wait. In some sites (in case of using browser autofill) the fields of login and password don’t get auto-filled at once. There is a delay until the page is completely loaded. That’s the delay till the DOMContentLoaded event.

Window.onbeforeunload¶

If a user has initiated navigation away from the page or intends to close the window, the beforeunload will ask for additional confirmation. In case of discarding the event, the browser will ask the user whether they are sure. See how to do it by running the following code and reloading the page, as shown below:

An interesting thing to note: returning a non-empty string also counts as aborting the event. Previously, the browsers used to show it as a message, but the modern specification doesn’t allow that.

Let’s take a look at an example:

The reason for changing the behaviour was that some webmasters abused the event handler by showing annoying messages. Still, old browsers may show messages, but there is no way of customizing the message.

HTML Reference

HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts

HTML Tags

<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

HTML Tags

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector