The lifecycle of an HTML page has three important events:
DOMContentLoaded – the browser fully loaded… Let’s say we gather data about how the page is used: mouse clicks, scrolls, viewed page areas, and so… The transition to another page is not delayed: the browser leaves the page, but still performs sendBeacon… If we want to cancel the transition to another page, we can’t do it here.… The typical output:
[1] initial readyState:loading
[2] readyState:interactive
[2] DOMContentLoaded
[
state
event.button
Left button (primary)
0
Middle button (auxiliary)
1
Right button (secondary)
2… (forward)
4
Most mouse devices only have the left and right buttons, so possible values are 0 or 2.… coordinates pageX/Y are counted from the left-upper corner of the document, and do not change when the page… When the page is scrolled, they change.… 500x500, and the mouse is in the left-upper corner, then clientX and clientY are 0, no matter how the page
This method must return the object with next() method returning a promise (2).… ”, and provides a URL to the next page.… It responds with a JSON of 30 commits, and also provides a link to the next page in the Link header.… We should get the next page URL from the Link header of the response.… The next page URL may look like https://api.github.com/repositories/93253246/commits?page=2.
Open the example page in Chrome.
Turn on developer tools with F12 (Mac: Cmd+Opt+I).… Navigator pane lists HTML, JavaScript, CSS and other files, including images that are attached to the page… For example, here 1+2 results in 3, while the function call hello("debugger") returns nothing… Breakpoints.Let’s examine what’s going on within the code of the example page… the debugger (after we’ve set the breakpoints) is to reload the page.
And it can’t be both version 1 and 2.… from 2 to 3, from 3 to 4 etc.… by step, for every intermediate version (2 to 3, then 3 to 4).… Get the store object using transaction.objectStore(name), at (2).… The examples are at the lib page https://github.com/jakearchibald/idb.
For compatibility, 2 digits are also accepted and considered 19xx, e.g. 98 is the same as 1998 here,… It returns 2-digit year sometimes. Please never use it. There is getFullYear() for the year.… Let’s say we need to increase the date “28 Feb 2016” by 2 days.… It may be “2 Mar” or “1 Mar” in case of a leap-year. We don’t need to think about it.… Just add 2 days.
functions are modal, they pause the code execution and prevent the visitor from interacting with the page… Assignments
There is a simple assignment: a = b and combined ones like a *= 2.… Parameters can have default values: function sum(a = 1, b = 2) {...}.
That’s a formalization of what we see when browsing a page.… So after some time, it raises an alert like “Page Unresponsive”, suggesting killing the task with the… whole page.… For example, syntax-highlighting (used to colorize code examples on this page) is quite CPU-heavy.… s clearly noticeable, and if you are running it in-browser, then try to click other buttons on the page
Image to blob.We can create a Blob of an image, an image part, or even make a page screenshot.… callbacks:
For screenshotting a page… What it does is just walks the page and draws it on <canvas>.… From Blob to stream.When we read and write to a blob of more than 2
In such case a web-browser suggests to kill the script and reload the page.… After some time it will suggest to reload the page.… The first number \d+ has 7 digits, and then a number of 2 digits:… The first number has 6 digits, and then 2… Here \2
Modules work only via HTTP(s), not locally
If you try to open a web-page locally, via file… This is the correct variant:
Resulthello.jsuser.jsindex.htmlIn the browser, if we talk about HTML pages… Here are two scripts on the same page, both type="module".… As you can see, when 1.js changes the name property in the imported admin, then 2.… run after that, so the user may see the page before the JavaScript application is ready.
There’s also an autofocus HTML attribute that puts the focus onto an element by default when a page loads… is: if we have two elements, the first has tabindex="1", and the second has tabindex="2&… The order is like this: 1 - 2
Wrote some code, testing: f(1) works, but f(2) doesn’t work. We fix the code and now f(2) works.… Here it checks that the result of pow(2, 3) equals 8.… The full HTML page with these frameworks and pow spec:… The page can be divided into five parts:
The <head> – add third-party libraries
It was a toy language to decorate a web page.
But web developers demanded more power.… People submitted it into <iframe>, just to stay on the current page, like this:… precise, there were actually tricks for that, they required special scripts at both the iframe and the page… For instance, if we request https://anywhere.com/request from https://javascript.info/page, the headers… Step 2 (preflight response).The server should respond with status 200 and the headers:
Access-Control-Allow-Origin
How to get an arbitrary element of the page?… The second scripts runs after the browser meets one more <div>, so its length is 2.
An exotic variable as a loop counter is especially cool if the loop body takes 1-2 pages (make it longer… For instance, the function printPage(page) will use a printer.
Origin – the origin of the client page, e.g. https://javascript.info.… codes like:
1001 – the party is going away, e.g. server is shutting down, or a browser leaves the page… values:
0 – “CONNECTING”: the connection has not yet been established,
1 – “OPEN”: communicating,
2
The internal format for strings is always UTF-16, it is not tied to the page encoding.… So .at(-1) means the last character, and .at(-2) is the one before it, etc.… To look for the next occurrence, let’s start the search from position 2:
So touch devices worked well with web pages.
But touch devices have more capabilities than a mouse.… As of now, Pointer Events Level 2 specification is supported in all major browsers, while the newer Pointer… Events Level 3 is in the works and is mostly compatible with Pointer Events level 2.
Step 2. Function Declarations.A function is also a value, like a variable.… If we call counter() multiple times, the count variable will be increased to 2,… You can always check for it by running the examples on this page.
An XMLHttpRequest object travels them in the order 0 → 1 → 2… It might look good, but synchronous calls are used rarely, because they block in-page
An errorless example: shows alert (1) and (2):… like this:
We register at the service and get a piece of JS (or a script URL) from them to insert on pages
is 2s, then the animation starts 1 second after the property change and the total duration will be 2… The calculations may take time, especially on pages with many elements and a complex layout.
For example, to calculate pow(2, 4) the recursive variant does these steps:
pow(2, 4) = 2 * pow(2, 3… )
pow(2, 3) = 2 * pow(2, 2)
pow(2, 2) = 2 * pow(2, 1)
pow(2, 1) = 2
So, the recursion reduces a function… Here’s the context stack when we entered the subcall pow(2, 2):
Context: { x: 2, n: 2, at line… n: 1, at line 1 }
pow(2, 1)
Context: { x: 2, n: 2, at line 5 }
pow(2, 2)… pow(2, 2)
Context: { x: 2, n: 3, at line 5 }
pow(2, 3)
The execution of pow(2, 2) is
The “clickjacking” attack allows an evil page to click on a “victim site” on behalf of the visitor.… Here’s how clickjacking was done with Facebook:
A visitor is lured to the evil page.… The demo.Here’s how the evil page looks.… The header may have 3 values:
DENY
Never ever show the page inside a frame.… A hacker can post a link to their evil page in a message, or lure visitors to their page by some other
If there’s a bulky script at the top of the page, it “blocks the page”.… For instance, we can put a script at the bottom of the page.… Dynamic scripts.There’s one more important way of adding a script to the page.… So the user can read page content and get acquainted with the page immediately.… will see the page before the script loads.
How do we scroll the page using JavaScript?… The method scrollBy(x,y) scrolls the page relative to its current position.… For instance, scrollBy(0,10) scrolls the page 10px down.… If top=false, then the page scrolls to make elem appear at the bottom.… The page will “freeze” at its current scroll position.
Otherwise, if the first digit is 2, then the next must be [0-3].… (no other first digit is allowed)
We can write both variants in a regexp using alternation: [01]\d|2[… If we glue hours and minutes together, we get the pattern: [01]\d|2[0-3]:[0-5]\d.… The alternation | now happens to be between [01]\d and 2[0-3]:[0-5]\d.… Let’s correct that by enclosing “hours” into parentheses: ([01]\d|2[0-3]):[0-5]\d.
There may be 2, 3, 4 or more.… In the demo above they are labeled: 1, 2, 3.
Build segments between control points 1 → 2 → 3.… 2 → 3, 3 → 4.… There will be N-2 segments.
Repeat step 2 until there is only one point.… 0 + 2(1−t)t * 0.5 + t2 * 1 = (1-t)t + t2 = t
y = (1−t)2 * 0 + 2(1−t)t * 1 + t2 * 0 = 2(1-t)t = –2t2 +
operand is 2.… The 2 gets concatenated to '1', so it’s like '1' + 2 = "12" and "12" + 2 = "… For example, write (1 + 2) * 2.
There are many operators in JavaScript.… So, the alert shows 2.… It’s like (a = 1 + 2), 3 + 4.
JavaScript was initially created to “make web pages alive”.… They can be written right in a web page’s HTML and run automatically as the page loads.… For instance, in-browser JavaScript is able to:
Add new HTML to the page, change the existing content… But even in this case, JavaScript from one page may not access the other page if they come from different… JavaScript can easily communicate over the net to the server where the current page came from.
DOM modification is the key to creating “live” pages.… Here we’ll see how to create new elements “on the fly” and modify the existing page content.… We’ll add a message on the page that looks nicer than alert.… It writes directly into the page text, while the DOM is not yet built.… To append HTML to the page before it has finished loading:
document.write(html)
After the page is loaded
When the page is scrolled to the very beginning, so that the top/left corner of the window is exactly… For instance click this button to see its window coordinates:
If you scroll the page and repeat, you… But note the important detail: when the page is scrolled, the message flows away from the button.… message element relies on position:fixed, so it remains at the same place of the window while the page… Relative to the document – elem.getBoundingClientRect() plus the current page scroll.
What’s interesting about them is that the data survives a page refresh (for sessionStorage) and even… …And close/open the browser or just open the same page… Another tab with the same page will have a different storage.… The data survives page refresh, but not closing/opening the tab.
Let’s see that in action.… You might want to open this page in two browser windows to test the code below.
Surrogate pairs.All frequently used characters have 2-byte codes (4 hex digits).… Initially, JavaScript was based on UTF-16 encoding that only allowed 2 bytes per character.… But 2 bytes only allow 65536 combinations and that’s not enough for every possible symbol of Unicode.… So rare symbols that require more than 2 bytes are encoded with a pair of 2-byte characters called “a… As a side effect, the length of such symbols is 2:
Most characters are encoded with 2 bytes, but that allows to represent at most 65536 characters.… are the Unicode values of some characters:
Character
Unicode
Bytes count in Unicode
a
0x0061
2… ≈
0x2248
2
𝒳
0x1d4b3
4
𝒴
0x1d4b4
4
😄
0x1f604
4
So characters like a and ≈ occupy 2 bytes… The point is that length treats 4 bytes as two 2-byte characters.… By default, regular expressions also treat 4-byte “long characters” as a pair of 2-byte ones.
The scroll event allows reacting to a page or element scrolling.… Load more data when the user scrolls down till the end of the page.
Web browsers give a means to control web pages. Node.js provides server-side features, and so on.… DOM (Document Object Model).The Document Object Model, or DOM for short, represents all page content… The document object is the main “entry point” to the page.… We can change or create anything on the page using it.… For instance, server-side scripts that download HTML pages and process them can also use the DOM.
Usually that header is set automatically and contains the url of the page that made the request.… "origin" – only send the origin in Referer, not the full page URL, e.g. only http://site.com… If we send a fetch, then by default it always sends the Referer header with the full url of our page… For example, we gather statistics on how the current visitor uses our page (mouse clicks, page fragments… When the visitor leaves our page – we’d like to save the data to our server.
One can also provide a relative path from the current page.… Other pages that reference the same script will take it from the cache instead of downloading it, so… That reduces traffic and makes pages faster.… We can use a <script> tag to add JavaScript code to a page.
second (*),
Then the .then handler is called (**), which in turn creates a new promise (resolved with 2… As the result is passed along the chain of handlers, we can see a sequence of alert calls: 1 → 2 → 4.… That handler is in the line (**), it shows 2 and does the same thing.… So the output is the same as in the previous example: 1 → 2 → 4, but now with 1 second delay between… In the example above resolve(2) is called after 1 second (**).
We can split user interface into visual components: each of them has own place on the page, can “do”… separate visual entity that we can describe in terms of what it does and how it interacts with the page… In the case above, the page has blocks, each of them plays its own role, it’s logical to make these components
It makes the cookie accessible for pages under that path. By default, it’s the current path.… Usually, we should set path to the root: path=/ to make the cookie accessible from all website pages.… can’t generate or extract from a remote page.… and waits for a user to visit that page.… Normally, if such a thing happens, and a user visits a web-page with a hacker’s JavaScript code, then
base=2 is mostly for debugging bitwise operations, digits can be 0 or 1.… several built-in functions for rounding:
Math.floor
Rounds down: 3.1 becomes 3, and -1.1 becomes -2.… -1
-1
-1
-1.5
-2
-1
-1
-1
-1.6
-2
-1
-2
-1
These functions cover all of the possible ways to deal… For instance, we have 1.2345 and want to round it to 2 digits, getting only 1.23.… It ensures that it has 2 digits after the decimal point.
…But please note: the example above shows 1, then 2, and that’s all. It doesn’t show 3!… It starts the execution and returns the result of the first yield "2+2=?".… For instance, here the yield of "2 + 2 = ?… The error, thrown into the generator at line (2)… The current line of the calling code is the line with generator.throw, labelled as (2).
For example, the pattern \b\d\d\b looks for standalone 2-digit numbers.… In other words, it looks for 2-digit numbers that are surrounded by characters different from \w, such
The multiplication obj * 2… first converts the object to primitive (that’s a string "2").… Then "2" * 2 becomes 2 * 2 (the string is converted to number).
browser several details about it: how to show it, what to do when the element is added or removed to page… method connectedCallback() – the browser calls it when <time-formatted> element is added to page… Not just appended to another element as a child, but actually becomes a part of the page.… They will only be actually rendered when they make it into the page.… We call it once when the element is inserted into page.
The word “modal” means that the visitor can’t interact with the rest of the page, press other buttons… are modal: they pause script execution and don’t allow the visitor to interact with the rest of the page
third-party script adds something into our document, and we’d like to detect, when it happens, to adapt our page… colored syntax highlighting into those elements, similar to what you see in examples here, on this page… Well, we can do it on DOMContentLoaded event, or put the script at the bottom of the page.… We can use MutationObserver to automatically detect when code snippets are inserted into the page and
Only first 50 results are shown.