JavaScript and the Browser
Execution Model
For each window / tab / frame:
- Load content
-
Render pages
Fetch additional ressources.
Process HTML, style sheets, scripts to display the page
-
React to events
User actions :
OnClick
,OnMouseover
, …Rendering :
OnLoad
,OnUnload
, …Timing:
setTimeout
,clearTimeout
, …
Embedding Javascript
Inlined in the page
<script>alert("Hello World!");</script>
Stored in external files
<script type="text/javascript" src="foo.js"></script>
Specified as event handlers
<a href="http://www.bar.com" onmouseover="alert('hi');">
Pseudo-URLs in links
<a href="javascript:alert('You clicked');">Click me</a>
DOM and BOM
APIs accessible through Javascript.
Browser Object Model BOM → interact with browser
Window
,Frames
,History
,Location
,Navigator
(browser type & version), ...
Document Object Model DOM → interact with HTML page
Properties:
document.forms
,document.links
, …
Methods:
document.createElement
,document.getElementsByTagName
, …
Example: Reading properties
<UL id="t1"> <LI>Item 1</LI> </UL>
document.getElementById('t1').nodeName // -> returns 'UL' document.getElementById('t1').getAttribute('id') // -> returns 't1' document.getElementById('t1').innerHTML // -> returns '<li>Item 1</li>' document.getElementById('t1').children[0].nodeName // -> returns 'LI' document.getElementById('t1').children[0].innerText // -> returns 'Item 1'
Example: Manipulating properties
let list = document.getElementById('t1'); let item = document.createElement('LI'); item.innerText = 'Item 2'; list.appendChild(item);
Example: Adding Event Handlers
let list = document.getElementById('t1'); list.addEventListener('click', (event) => { alert(`Clicked: ${event.target.innerText}`); });