0% found this document useful (0 votes)
2 views13 pages

Introduction To JavaScript in HTML

Introduction to javascript

Uploaded by

arnoldndoli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Introduction To JavaScript in HTML

Introduction to javascript

Uploaded by

arnoldndoli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to JavaScript in HTML

Executive Summary: HTML’s <script> element embeds executable code or


data (usually JavaScript) into a webpage【40†L213-L216】. This allows
dynamic behavior: responding to user events, manipulating content, and
adding interactivity. The <script> tag supports attributes like src, type,
async, defer, nomodule, crossorigin, and integrity to control loading and
execution. Placement of scripts (in <head> vs end-of-<body>) affects parsing
and rendering performance. JavaScript can run inline (inside
<script>…</script>) or as external files, and ES modules (<script
type="module">) bring modern module support (with automatic deferral). To
manipulate the DOM, scripts use methods like getElementById,
querySelector, and properties like innerHTML, textContent, classList, and
dataset. Best practices include using defer or putting scripts at the end of
<body> to avoid render-blocking【3†L492-L501】, adding Subresource Integrity
(integrity attribute) and CORS (crossorigin) on external scripts【1†L375-
L382】【1†L324-L330】, avoiding unsanitized HTML to prevent XSS (prefer
textContent over innerHTML for user data【24†L292-L301】【24†L312-L314】),
and employing a strict Content-Security-Policy (using nonces or hashes for
any inline code【30†L389-L397】). Common pitfalls include variable hoisting
(e.g. using var before declaration yields undefined【32†L200-L207】), scope
mistakes (use let/const for block scope), and async timing issues
(unpredictable order with async or race conditions with Promise callbacks).
Developer tools (console, debugger) and careful event handling
(DOMContentLoaded vs load) help with debugging. This note covers these
concepts with examples, tables, and a loading-order diagram, citing MDN
and standards.

Purpose of Embedding JavaScript


The <script> element embeds executable code or data into
HTML【40†L213-L216】. Typically this is JavaScript, which enables dynamic
page behavior: updating content, responding to user input, performing
calculations, communicating with servers, etc. By placing <script> in HTML,
developers can access and modify the DOM, listen to events (clicks,
keyboard, page load), and control presentation dynamically. (Aside from JS,
<script> can technically include other code/data types like GLSL shaders or
JSON, but JavaScript is by far the most common【40†L213-L216】.) Embedding
scripts directly connects code to the page and is central to modern web
interactivity.

<script> Tag Syntax and Attributes


The <script> element has two core attributes:
 type: indicates the script type. The default (omitted or empty) is a
classic JavaScript script. For ES modules, use type="module", which
treats the code as a module (deferred by default, supports
import/export, requires CORS for cross-origin)【30†L453-L459】. Other
type values like "importmap" or "speculationrules" have special uses
(import maps or speculation rules), but are advanced. If type is a non-
JS MIME type, the content is treated as a data block, not
executed【36†L123-L132】.
 src: the URL of an external script file【3†L430-L438】. If src is present,
the browser fetches that file instead of using inline code.
Beyond these, important script attributes include:

Attribute Description / Effect


async Boolean. For external scripts:
fetch script in parallel to
parsing and execute as soon
as it’s ready【40†L232-L240】
【3†L524-L532】. This does not
block parsing during fetch,
but does block rendering
when the script executes.
Scripts run in no guaranteed
order. (Not applicable to
inline scripts.) Use async when
scripts are independent.
【3†L524-L532】
defer Boolean. For external classic
scripts: fetch in parallel
without blocking parse, and
execute after HTML parsing
is complete, in document
order【40†L332-L340】【3†L533-
L536】. The scripts run just
before the DOMContentLoaded
event【1†L334-L343】. This
prevents scripts from blocking
the initial page load. (Has no
effect on inline scripts.) For
modules, defer is implied by
default【30†L453-L459】.
nomodule Boolean. If present on a classic
<script>, it prevents
execution in browsers that
support ES modules【30†L383-
Attribute Description / Effect
L390】. Use it to provide
fallback scripts for older
browsers when you also
include <script
type="module"> variants.
crossorigin Controls CORS mode for the
script fetch. For example,
crossorigin="anonymous"
allows the script to be fetched
across origins with no
credentials. It also enables full
error reporting (otherwise
cross-origin errors are opaque)
【1†L324-L330】. Required
when using integrity with
cross-origin scripts (see
below).
integrity Contains a cryptographic hash
(e.g. SHA-256) of the script.
The browser will verify the
fetched script matches this
hash, preventing tampering
(Subresource Integrity)
【1†L375-L382】. If the hash
check fails, the script is not
executed. Do not use without
src.
nonce A server-generated
cryptographic nonce value.
When using a strict CSP
(script-src), an inline
<script> block can be allowed
only if its nonce matches the
policy【30†L389-L397】. This
lets you keep some inline
scripts while still enforcing
CSP.

Scripts without async, defer, or type="module" (and inline scripts without


module) are parser-blocking by default【3†L492-L500】: the browser stops
building the DOM, fetches the script, executes it, then resumes parsing. In
practice, a script tag in <head> with no attributes will delay page parsing and
rendering until that script is done【3†L492-L500】. Using defer or placing
scripts at the end of <body> avoids this blocking.
<script> Attributes Summary
Attribute Usage Behavior
type module / (default) "module" treats
code as ES module
(auto-deferred).
Default (or
text/javascript) is
classic JS【30†L453-
L459】.
src URL of external Fetch this file
script instead of inline
content【3†L430-
L438】.
async (boolean) Parallel fetch,
execute ASAP
(blocks render on
execution),
unpredictable
order【40†L232-
L240】【3†L524-
L532】.
defer (boolean) Parallel fetch,
execute after parse
completes (blocks
DOMContentLoaded
until done)【1†L334-
L343】【3†L533-
L536】.
nomodule (boolean) Don’t run this script
in browsers with
module support
(fallback for old
browsers)
【30†L383-L390】.
crossorigin "anonymous"/"use- Set CORS fetch
credentials" mode; needed for
SRI and full error
reporting【1†L324-
L330】.
integrity hash (e.g. SHA-256) Verify script
matches expected
hash (SRI)【1†L375-
L382】; use with
Attribute Usage Behavior
crossorigin.

Script Placement (Head vs Body)


Where you put <script> tags affects page loading:
 In <head> (no defer/async): The script is fetched and executed before
the HTML body is parsed. This blocks the parser, so the user sees a
blank page until the script loads. Use this only if the script must run
immediately and does not depend on DOM content.
 In <head> with defer: Scripts download in parallel with parsing and
execute after parsing ends (before DOMContentLoaded)【1†L334-L343】.
This is often ideal: it keeps scripts in head (clean separation) without
blocking render.
 At end of <body> (just before </body>): Effectively similar to defer
without using the attribute. By the time the parser reaches scripts at
the end, the DOM is mostly built, so the page content appears first.
The script still blocks any further parsing (which is minimal) and runs,
then triggers DOMContentLoaded/load. This pattern was historically
common for performance【15†L994-L1001】.
 With async: Placement matters less for blocking, since async scripts
may execute whenever they finish loading. Even if placed in head,
they’ll load in parallel and may run before the body is parsed (blocking
only momentarily on execution). Order is unpredictable, so use async
only for independent scripts (e.g. analytics)【3†L524-L532】.
A summary of placement trade-offs:

Parsing/Rendering
Placement Effect Notes
<head> (classic Blocks HTML Can delay showing
script) parsing and content; avoid if
rendering until heavy.
download &
execution
finish【3†L492-
L500】.
<head> with defer HTML parsing not Good for scripts
blocked; scripts run that need DOM, still
after parse (before keep in head.
DOMContentLoaded)
【1†L334-L343】.
End of <body> HTML parsed fully Page content
(classic) first; script runs, appears before
Parsing/Rendering
Placement Effect Notes
then script
DOMContentLoaded/l runs【15†L994-
oad. L1001】.
Anywhere with HTML parsing Rendering
async continues during temporarily halted
fetch; script on execute; no
executes as soon order
as ready (blocking guarantee【3†L524-
for its execution L532】.
time).
flowchart LR
A[Start parsing HTML] --> B{Encounter &lt;script&gt;}
B -->|no async/defer| C[Fetch script (blocking)]
B -->|async present| D[Fetch script (parallel)]
B -->|defer present| E[Fetch script (parallel)]
D --> F{Script downloaded}
C --> F
E --> F
F -->|if async| G[Execute script immediately (blocks parse)]
F -->|if defer| H[Wait until after HTML parse]
H --> I[Execute script (in order, before DOMContentLoaded)]
G --> I
I --> J[Resume/Finish parsing]

Inline vs External Scripts


 Inline <script> (e.g. <script>[Link]("Hello");</script>)
contains code directly in the HTML. It has no src and runs exactly at
that point in the document. Benefits: no extra HTTP request; can
manipulate page content that appears before it. Drawbacks: cannot be
cached separately, mixes code with markup, and generally should be
minimized (especially because inline code is harder to secure under
CSP and can bloat HTML).
 External <script src="[Link]"> loads code from a separate
file【3†L430-L438】. Benefits: browser can cache the file (good for
performance and reuse), keeps HTML clean, and allows content to be
modular. The drawback is the additional request (but this is usually
worth it for larger scripts).
A quick pros/cons:

External Script
Inline Script (src)
Loading Runs immediately Fetch separately
where placed (can use
External Script
Inline Script (src)
(blocking unless async/defer).
async/defer on
external).
Caching No (fits only that Yes (cached across
HTML document). pages/visits).
Organization Code embedded in Keeps code in .js
HTML (less files (better
maintainable). organization).
Security Harder to enforce Easiest to control
strict CSP (requires with CSP; can use
unsafe-inline or SRI (integrity) and
nonces)【24†L292- crossorigin.
L301】【30†L389-
L397】.

ES Modules (<script type="module">)

Modern JavaScript uses modules. Using <script type="module"> tells the


browser to treat the script as an ES module:
 Module scripts automatically defer (they run after the document is
parsed, like defer)【30†L453-L459】【36†L268-L274】.
 Inside a module script, you can use import and export.
 Modules use CORS by default when loading imports from other
domains (you must serve with proper CORS headers).
 You can mark a fallback classic script with nomodule so older browsers
load a non-module version【30†L383-L390】. Example:
<script type="module" src="[Link]"></script>
<script nomodule src="[Link]"></script>

This loads [Link] in modern browsers and [Link] in older ones.


Modules also enable strict mode and have their own scope. Using modules is
recommended for larger apps. (For basic scripts, you can use classic mode
and still use async/defer as needed.)

DOM Basics and JavaScript Interaction


JavaScript interacts with the HTML DOM to select and manipulate
elements. Key methods/properties:
 [Link]("id"): returns the element with that id
(unique per page)【18†L209-L217】. Fast for known IDs.
 [Link](selector): returns the first element matching
a CSS selector (like .class, #id, div > p, etc.)【20†L210-L218】. More
flexible for complex queries. (querySelectorAll returns all matches.)
 Event Listeners: To respond to events (clicks, keypresses, loads,
etc.), use [Link](eventType, handler). This is the
recommended way to attach event handlers【22†L298-L300】. For
example:
[Link]("click", () => {
// code runs when button clicked
});

You can attach multiple listeners to the same event. Avoid inline event
attributes (onclick="...") as they mix HTML/JS and are not CSP-friendly.
 innerHTML / textContent:
 [Link] = "<b>Hi</b>" sets the element’s HTML content.
Danger: inserting raw HTML can introduce XSS if the content is not
sanitized【24†L292-L301】. Browsers try to block scripts inside
innerHTML, but attackers can use events (e.g. <img onerror=...>). Use
with caution, or better use sanitization (e.g. DOMPurify) or trusted
types.
 [Link] = "Hello" sets text content (no HTML parsing). It’s
safe for untrusted text. MDN advises preferring textContent for plain
text to avoid XSS risks【24†L312-L314】.
 classList: [Link] is a DOMTokenList of the element’s
classes【26†L209-L214】. You can use add(), remove(), toggle(), and
contains() to modify classes easily, instead of messing with the string
[Link]. Example: [Link]("active").
 dataset: [Link] is a map (DOMStringMap) of custom data-*
attributes【28†L206-L214】. For example, <div
data-user-id="123"></div> lets you access [Link] ===
"123". This makes it easy to store extra info in HTML. (The attribute
data-foo-bar="x" becomes [Link] in JS.)

Example of selecting and modifying an element:


<p id="demo"></p>
<script>
const p = [Link]("demo"); // select
element
[Link] = "Hello, world!"; // set its text
[Link]("highlight"); // add a CSS
class
[Link] = new Date().toISOString(); // add a data-
time attribute
[Link]("click", () => alert("Clicked!")); // handle
click
</script>
Loading and Execution Order
The browser parses HTML top-down. When it encounters <script> tags, the
following happens depending on attributes:
1. Classic script (no async/defer): Parsing pauses. The browser
downloads the script (if src) and then executes it immediately. Only
then parsing resumes【3†L492-L500】. This means scripts in <head>
block the page from loading further content.
2. Async script: The script starts downloading in parallel with
parsing【40†L232-L240】. When it finishes downloading, parsing pauses
for its execution, then resumes. There’s no guaranteed order relative
to other scripts or DOM readiness【3†L524-L532】.
3. Defer script (classic): The script downloads in parallel as the page
parses【1†L334-L343】. It executes after the HTML parse is complete
(just before firing DOMContentLoaded), and scripts keep the order they
appear. The DOM is fully built by the time these scripts run.
4. Module script: Behaves like defer by default (download in parallel,
execute after parsing)【30†L453-L459】【36†L268-L274】. If marked
async, it can execute as soon as ready.

The following diagram summarizes these modes:


sequenceDiagram
participant Parser as HTML Parser
participant Script as <script> Tag

Parser->>Parser: Parse HTML until &lt;script&gt;


Parser->>Script: Encounter &lt;script src="[Link]"&gt;
alt Classic (no async/defer)
Script->>Script: Fetch and execute (blocks Parser)
Script-->>Parser: After execution, continue parsing
else Async (with async)
Parser->>Script: Fetch in parallel
Script-->>Parser: When fetched, execute (pauses parsing)
Parser->>Parser: Continue parsing
else Defer (with defer)
Parser->>Script: Fetch in parallel
Parser->>Parser: Continue parsing to end (DOM built)
Script->>Parser: Execute (in order, before DOMContentLoaded)
end
Parser->>Parser: HTML parsed; DOMContentLoaded fires

In practice, use developer tools (browser console, network panel) to


observe this order. The DOMContentLoaded event fires when parsing is done
and all deferred scripts have run. The load event fires later when all images
and resources are loaded.
Performance and Security Best Practices
 Avoid blocking rendering: Prefer defer or put scripts at end of
<body>. Use async only when script does not depend on other code or
the DOM. This improves page load performance【3†L492-L500】
【1†L334-L343】.
 Cache and bundle scripts: Serving external JS files allows browser
caching. Minify and bundle scripts to reduce size and requests (not
covered here, but standard practice).
 Content Security Policy (CSP): Use a CSP header (Content-
Security-Policy: script-src 'self' 'nonce-...'; etc.) to restrict
allowed script sources. Avoid unsafe-inline. To allow necessary inline
scripts, use nonce attributes【30†L389-L397】. E.g. <script
nonce="ABC123">...</script> with CSP script-src 'nonce-ABC123'.
This prevents XSS by disallowing unknown scripts.
 Sanitize user input: Never inject unsanitized user data into the DOM
as HTML. Use textContent or careful templating. If you must insert
HTML from users, use libraries like DOMPurify to clean it first.
 Use SRI and CORS: For third-party or CDN scripts, include
integrity="sha256-..." and crossorigin="anonymous" to ensure the
code isn’t tampered【1†L375-L382】【1†L324-L330】. This prevents
supply-chain attacks.
 Set correct MIME types: Serve scripts with Content-Type:
text/javascript. Browsers may block a <script> if served with a
disallowed MIME (e.g. image or audio types)【30†L492-L500】.
 Avoid innerHTML for untrusted content: It’s a common XSS
vector【24†L292-L301】. The MDN docs warn that innerHTML “is
probably the most common vector for XSS attacks”【24†L292-L301】.
Use textContent to insert text safely【24†L312-L314】. When adding
HTML, sanitize or use TrustedHTML.
 Avoid global variables: Limit global scope. Use modules or IIFEs to
avoid polluting the global namespace.

Debugging Tips and Common Pitfalls


 Console and DevTools: Use [Link](), breakpoints, and
stepping in the browser devtools to trace code. The console ( F12)
shows errors with line numbers. Enable “Pause on exceptions” to catch
crashes.
 Hoisting: In JavaScript, declarations are “hoisted” to the top of their
scope【32†L200-L207】. For example, using var x before its declaration
yields undefined. Always declare variables before use, or better, use
let/const which have block scope and no silent hoisting. MDN glossary
defines hoisting as moving declarations to the top of scope【32†L200-
L207】.
 Scope: Remember that var is function-scoped, while let and const are
block-scoped. Using var in a loop can lead to shared scope bugs. Prefer
let/const.
 Timing issues: Scripts with async can finish at unpredictable times,
causing race conditions (one script may run before another finishes).
For sequential dependencies, use defer or load scripts in order. If using
AJAX or fetch(), chain promises (.then()) or use async/await to ensure
order.
 DOMContentLoaded vs load: The DOMContentLoaded event fires
when the HTML is parsed and deferred scripts have run, but before
images/stylesheets finish loading. The load event fires later when all
resources are done. Use DOMContentLoaded to run code as soon as the
DOM is ready. For example:
<script>
[Link]('DOMContentLoaded', () => {
[Link]("DOM fully parsed");
});
[Link]('load', () => {
[Link]("All resources loaded (images, etc.)");
});
</script>

If scripts are in <head> without defer, they block DOMContentLoaded until


executed (as noted above).
 Error messages: Uncaught errors usually appear in console. Use
[Link]() or break on exceptions. A <script> tag will fire an
error event if loading fails or the MIME type is incorrect【30†L492-
L500】.

Example Snippets
Inline Script Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline Script Demo</title>
</head>
<body>
<p id="greet">Hello, <span id="name"></span>!</p>
<script>
// Inline JavaScript that runs immediately
[Link]('name').textContent = 'world';
</script>
</body>
</html>
Here the inline <script> sets the text inside #name as soon as the parser
reaches it.
External Script Example:
HTML:
<script src="[Link]"></script>

[Link]:

// [Link]
[Link]('demo').innerHTML = "Loaded from external
file";

This fetches [Link] (which can be cached) and then executes it.
Async vs Defer Example:
<script async src="[Link]"></script>
<script defer src="[Link]"></script>

- [Link] (async) will load in parallel and run as soon as it’s ready
(independent of other scripts).
- [Link] (defer) will load in parallel but wait to execute until after HTML
parsing (and after any earlier defer scripts).
Module Script Example:
<script type="module">
import { greet } from './[Link]';
[Link] = greet('Alice');
</script>

In this module, you can use import. It runs after parsing (like defer).
DOMContentLoaded vs Load Demo:
<!DOCTYPE html>
<html>
<head>
<script>
[Link]('DOMContentLoaded', () => {
[Link]("DOMContentLoaded: DOM is ready.");
});
[Link]('load', () => {
[Link]("Load: All resources are loaded.");
});
</script>
</head>
<body>
<img src="[Link]" alt="Demo Image">
<p>Content of the page.</p>
</body>
</html>

This shows that DOMContentLoaded fires before load (which waits for the
image).

Learning Resources
 MDN Web Docs: Comprehensive references and guides. Key pages:
“<script> HTML element”, JavaScript fundamentals, and DOM
guides【40†L213-L216】【18†L209-L217】【22†L298-L300】. MDN’s
JavaScript and Web API docs are prioritized for beginners.
 WHATWG HTML Standard: The living HTML spec (script section)
details <script> behavior, including async/defer【36†L260-L268】
【36†L268-L274】.
 ECMAScript (JavaScript) Specification: The official language spec
(ECMA-262) defines modules, syntax, and behavior (useful for deep
dives on modules, classes, etc.). The 2027 edition is on [Link].
 W3C DOM Specification: For DOM interfaces and events (e.g.
getElementById, event model).
 Security References: OWASP XSS Prevention, Content Security Policy
guidelines, and libraries like DOMPurify for sanitization.
Prioritized sources: Start with MDN (learning guides and references). For
standards-level detail, consult the WHATWG HTML spec and the ECMAScript
spec. W3C and browser blogs also offer authoritative advice on performance
and security best practices.

You might also like