Dorokhov.codes
07. Platform: browser
Adding scripts
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
console.log("Test");
</script>
</body>
</html>
<script src="js/script.js"></script>
Deprecated variant:
<script src="js/script.js" type="text/javascript"></script>
Remember to include JS before the closing body
tag.
defer attribute
Scripts with the defer
attribute do not block the HTML parsing process. They are executed only after DOM is fully constructed. It means that we can get rid of
DOMContentLoaded
event listener. And they are executed in the order they appear.
<script defer src="js/script1.js"></script>
<script defer src="js/script2.js"></script>
async attribute
Unlike defer
, scripts with the async
attribute are executed as soon as they are loaded, without waiting for the DOM is ready.
This can lead to scripts being executed in an unpredictable order.
The async attribute is best suited for scripts that do not depend on the DOM or other scripts, such as analytics or tracking scripts.
<script async src="js/script1.js"></script>
<script async src="js/script2.js"></script>
Dynamic script adding
const script = document.createElement('script');
script.src = 'js/script.js';
script.async = false; // By default the async attribute is true.
document.body.append(script);
Features
Feature | Comment |
---|---|
Document Object Model | The DOM is a programming interface for web documents, allowing scripts to manipulate structure, style, and content. |
Local storage | A web storage API that allows storing key-value pairs in the browser, persisting even after the browser is closed. |
Cookies | Small text files used to store user-specific data, such as session identifiers or preferences, on the client side. |
Browser specific functions
Prompt
Prompt user for some text string:
// Second parameter is a placeholder (default value).
var name = prompt("What's your name?", "Andrew");
console.log("Hi, " + name + "!");
If a user clicks “Cancel”, the name
variable will get null
. So, if we want to check
if the user clicked “Cancel”:
if (name != null) { ... }
Confirm
var userAgrees = confirm("Do you agree?");
if (userAgrees) {
console.log("Let's do it!");
}
Alert
alert("Some message");