Javascript урок11. объектная модель документа (продолжение) и идентификация

What is the window onload event in javascript?

JavaScript

JS Array
at()
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
flat()
flatMap()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
lastIndexOf()
length
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()
sinh()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

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

JS Object
constructor
keys()
prototype
toString()
valueOf()

JS OperatorsJS PrecedenceJS RegExp
Modifiers:
g
i
m
Groups:

(x|y)
Metacharacters:
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx
Quantifiers:
+
*
?
{X}
{X,Y}
{X,}
$
^
?=
?!
Properties:
constructor
global
ignoreCase
lastIndex
multiline
source
Methods:
compile()
exec()
test()
toString()

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

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

JS TypedArray

HTML Events

HTML Events
abort
afterprint
animationend
animationiteration
animationstart
beforeprint
beforeunload
blur
canplay
canplaythrough
change
click
contextmenu
copy
cut
dblclick
drag
dragend
dragenter
dragleave
dragover
dragstart
drop
durationchange
ended
error
focus
focusin
focusout
fullscreenchange
fullscreenerror
hashchange
input
invalid
keydown
keypress
keyup
load
loadeddata
loadedmetadata
loadstart
message
mousedown
mouseenter
mouseleave
mousemove
mouseover
mouseout
mouseup
offline
online
open
pagehide
pageshow
paste
pause
play
playing
progress
ratechange
resize
reset
scroll
search
seeked
seeking
select
show
stalled
submit
suspend
timeupdate
toggle
touchcancel
touchend
touchmove
touchstart
transitionend
unload
volumechange
waiting
wheel

HTML Event Objects
Animation Events
Clipboard Events
Drag Events
Events
Focus Events
HashChange Events
Input Events
Keyboard Events
Mouse Events
PageTransition Events
PopState Events
Progress Events
Storage Events
Touch Events
Transition Events
Ui Events
Wheel Events

HTML Event Properties
altKey (Mouse)
altKey (Key)
animationName
bubbles
button
buttons
cancelable
charCode
clientX
clientY
code
ctrlKey (Mouse)
ctrlKey (Key)
currentTarget
data
defaultPrevented
deltaX
deltaY
deltaZ
deltaMode
detail
elapsedTime
elapsedTime
eventPhase
inputType
isTrusted
key
keyCode
location
metaKey (Mouse)
metaKey (Key)
newURL
oldURL
offsetX
offsetY
pageX
pageY
persisted
propertyName
relatedTarget
relatedTarget
screenX
screenY
shiftKey (Mouse)
shiftKey (Key)
target
targetTouches
timeStamp
touches
type
which (Mouse)
which (Key)
view

HTML Event Methods
getModifierState()
preventDefault()
stopImmidiatePropagation()
stopPropagation()

HTML Теги

<!—><!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><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><keygen><label><legend><li><link><main><map><mark><menu><menuitem><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><table><tbody><td><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

JavaScript

JS Массивы
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 Булевы
constructor
prototype
toString()
valueOf()

JS Классы
constructor()
extends
static
super

JS Даты
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 Ошибка
name
message

JS Булевы
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()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Числа
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS ОператорыJS Рег.Выражения
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 Заявления
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS Строки
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()

Associating a call back with an event

Associating a call back with an event is illustrated in the following
program.

In this example, the click event (called onClick) is associated with the
function pressFunction, which is metadata and defined in the head of the
html page. When a user clicks on the button that says, “Press me”, it
calls the function associated with the click even, the pressFunction,
and an alert box is shown saying “You pressed me”.

This is the complete life cycle of events and call backs. An event
(click) is mapped to a callback function (pressFunction). When the event
is raised (the user clicks the button), the event call back function is
called.

The rest of this section will explain how you should implement these in
JavaScript.

Example HTML code 2:

This example illustrates the use of the onload event for img elements:

<head><scripttype="text/javascript">// Internet Explorer specific
function OnAbortImage () {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />The loading of the image has been aborted.";
            RemoveEsc ();
        }

        function OnLoadImage () {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />The image has been loaded.";
            RemoveEsc ();
        }

            // Internet Explorer specific
function OnStateChangeImage (image) {
            var info = document.getElementById ("info");
            info.innerHTML += "<br />readyState: " + image.readyState;
        }

        function RemoveEsc () {
            var esc = document.getElementById ("esc");
            esc.parentNode.removeChild (esc);
        }
    </script></head><body><spanid="info"style="color:red">The image is loading.</span><br/><br/><spanid="esc">Press the Escape key to abort the process.</span><br/><br/><imgsrc="large.bmp"width="200px"height="150px"onabort="OnAbortImage ()"onload="OnLoadImage ()"onreadystatechange="OnStateChangeImage (this)"/></body>

Did you find this example helpful?

yes
no

window.onunload

Когда посетитель покидает страницу, на объекте window генерируется событие unload . В этот момент стоит совершать простые действия, не требующие много времени, вроде закрытия связанных всплывающих окон.

Обычно здесь отсылают статистику.

Предположим, мы собрали данные о том, как используется страница: клики, прокрутка, просмотры областей страницы и так далее.

Естественно, событие unload – это тот момент, когда пользователь нас покидает и мы хотим сохранить эти данные.

Для этого существует специальный метод navigator.sendBeacon(url, data) , описанный в спецификации https://w3c.github.io/beacon/.

Он посылает данные в фоне. Переход к другой странице не задерживается: браузер покидает страницу, но всё равно выполняет sendBeacon .

Его можно использовать вот так:

  • Отсылается POST-запрос.
  • Мы можем послать не только строку, но так же формы и другие форматы, как описано в главе Fetch, но обычно это строковый объект.
  • Размер данных ограничен 64 Кб.

К тому моменту, как sendBeacon завершится, браузер наверняка уже покинет страницу, так что возможности обработать ответ сервера не будет (для статистики он обычно пустой).

Для таких запросов с закрывающейся страницей есть специальный флаг keepalive в методе fetch для общих сетевых запросов. Вы можете найти больше информации в главе Fetch API.

Если мы хотим отменить переход на другую страницу, то здесь мы этого сделать не сможем. Но сможем в другом месте – в событии onbeforeunload .

The onload Function

The object in JavaScript has an event handler called . When this event handler is used, the entire page and all of its related files and components are loaded before the function listed in the event handler is executed, hence the term “on load.”

As shown in the script above, it’s easy to use, but what if you have more than one function you want to call using an event handler?

You would think you could just stack them like this:

window.onload=func1;<br />
window.onload=func2;<br />
window.onload=func3;<br />

Unfortunately, it’s not that simple. After the first event handler is executed, it will be replaced when the second event handler is executed. That, in turn, will be replaced immediately just as soon as the third event handler is executed. There are workarounds for this, though.

Let’s Put Them in a Chain

One method that has been used quite a bit is the linking of multiple events. It places several function calls in a chain, using one event handler. The method would look like this:

<body onload=”func1(); func2();”>

Still, once again we run into the unobtrusive problem. In addition, you will need to add this to the tag of every page that needs to use the called functions. That could be quite tedious for a large Web site, especially when changes or additions are needed.

Within Another Function

Another method is the following script:

function start() {<br />
func1();<br />
func2();<br />
}<br />
window.onload = start;<br />

While this is good, there’s one method that’s even better.

The Function

function addLoadEvent(func) {<br />
var oldonload = window.onload;<br />
if (typeof window.onload != ‘function’) {<br />
window.onload = func;<br />
} else {<br />
window.onload = function() {<br />
if (oldonload) {<br />
oldonload();<br />
}<br />
func();<br />
}<br />
}<br />
}<br />
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);<br />
addLoadEvent(function() {<br />
/* more code to run on page load */<br />
});<br />

This function was written by Simon Willison. It has several advantages. For one, it’s really unobtrusive. It can be placed in a file with your other scripts or in a separate file. (If it’s in a separate file, just be sure to call it after the other files, so the functions will be available.)

Also, it works even if the event handler has been previously assigned. Simon explains it like this:

Isn’t that beautiful? So, if you already have a script that uses the event handler, you don’t need to dig it out and change it, unless you want to. It also allows for extra code. Here’s an example that calls two functions and adds a third, independent :

function func1() {<br />
alert(“This is the first.”);<br />
}<br />
function func2() {<br />
alert(“This is the second.”);<br />
}</p>
<p>function addLoadEvent(func) {<br />
var oldonload = window.onload;<br />
if (typeof window.onload != ‘function’) {<br />
window.onload = func;<br />
} else {<br />
window.onload = function() {<br />
if (oldonload) {<br />
oldonload();<br />
}<br />
func();<br />
}<br />
}<br />
}<br />
addLoadEvent(func1);<br />
addLoadEvent(func2);<br />
addLoadEvent(function() {<br />
document.body.style.backgroundColor = ‘#EFDF95’;<br />
})<br />

After calling and , a function is created that changes the background color of the Web page. Each of these is executed in the order shown. Try it yourself and see how it works!

Using the window.onload Event in JavaScript

Here, we have a second approach for calling the function on page load in JavaScript. Every web page contains the window object by default, and the window object represents the global variables. We can access any global variable or function in JavaScript using the window object. In this approach, we will use the onload property of the window object.

By using the window.onload property, users can either call a named function or bind an anonymous function to the window.onload and all code inside the anonymous function will be executed after the page load.

Syntax

Users can follow the below syntax to use the window.onload to call a function on page load.

Syntax for anonymous function.

Window.onload = function {
   // code to execute on the page load
}

Syntax for named function.

Function simpleFunction ( ) {
   // function body
}
Window.onload = simpleFunction( );

Example

In the below example, we are calling the named function on the page load using the window.onload property.

<html>
<head>
   <title> Call JavaScript function on page load. </title>
</head>
<body>
   <h2> Methods to call a JavaScript function on page load. </h2>
   <h4> Call the JavaScript function on page load by using <i>window.onload</i> event in the JavaScript. </h4>
   <div id="message"> </div>
   <script type="text/javascript">
      window.onload = simpleFunction( 10, 20 ); // call function with parameters on page load
      function simpleFunction( num1, num2 ) {
         alert(" The sum of num1 and num2 is " + ( num1 + num2 ) );
         message.innerHTML = "Showing the message after alert box."
      }
   </script>
</body>
</html>
Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: