효율적인 스크립트 로딩 전략
JavaScript를 비동기적으로 로드하고 중요하지 않은 스크립트의 실행을 지연하며 모듈 패턴을 효과적으로 사용하는 기법을 익힙니다.
효율적인 스크립트 로딩 전략은(는) CoddyKit의 무료 Web Performance Optimization & Lighthouse 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Performance Optimization & Lighthouse 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Fast Scripts, Fast Pages
JavaScript powers interactive web experiences. But if not loaded efficiently, it can significantly slow down your website.
A slow loading script can block your page from rendering, making users wait longer to see and interact with content.
In this lesson, we'll explore strategies to load scripts smartly, ensuring your users get a smooth, fast experience.
Scripts Block Rendering
By default, when a browser encounters a <script> tag in your HTML, it pauses parsing the HTML document.
It fetches, parses, and executes the script immediately. Only after the script finishes can HTML parsing resume.
This can be a major bottleneck, especially for large scripts. Try running this simple script to see how it can simulate a blocking operation:
console.log("HTML parsing paused (simulated).");
// Simulate a computationally heavy task
let sum = 0;
for (let i = 0; i < 100000000; i++) {
sum += i;
}
console.log("Blocking script finished. Sum:", sum);
console.log("HTML parsing resumes (simulated).");`async`: Load in Parallel
The async attribute tells the browser to download the script in parallel with parsing the HTML document.
- Non-blocking: HTML parsing continues while the script downloads.
- Execute immediately: The script executes as soon as it's downloaded, without waiting for the HTML to finish parsing.
- Order not guaranteed: Scripts with
asyncmight execute in any order, potentially out of the order they appear in the HTML.
Use async for independent scripts like analytics or ads that don't rely on other scripts or the full DOM.
`async` in Action
Imagine this script is loaded with <script async src="my-async-script.js"></script>.
It downloads in the background, and once ready, runs right away. Other page content can continue loading.
Notice how "Page content continues..." might appear before "Async script finished" in a real browser scenario, as the script doesn't block.
console.log("Async script started downloading.");
// Simulate fetching data or setting up a listener
setTimeout(() => {
console.log("Async script finished execution.");
}, 50); // Small delay to simulate download + execution
console.log("Page content continues to load in parallel.");`defer`: Execute After HTML
The defer attribute also makes scripts non-blocking, but with a key difference in execution time.
- Non-blocking: Like
async, the script downloads in parallel with HTML parsing. - Execute after HTML: The script executes only after the HTML document has been completely parsed.
- Order guaranteed: Scripts with
deferexecute in the exact order they appear in the HTML.
defer is ideal for scripts that depend on the full DOM, like interactive elements or form validations, but don't need to block initial rendering.
`defer` in Action
This script, loaded with <script defer src="my-defer-script.js"></script>, would wait for all HTML to be processed before running.
It's perfect for scripts that need to interact with elements on the page without blocking the user from seeing content first.
console.log("Defer script started downloading.");
// Simulate DOM manipulation or event setup
setTimeout(() => {
// In a real browser, document.getElementById would now work.
console.log("Defer script finished execution after HTML parsed.");
}, 50); // Small delay
console.log("HTML parsing completed (simulated) before defer script runs.");Pick Your Strategy
Understanding the differences between async and defer is crucial for optimal performance:
async: For independent scripts that don't care about DOM readiness or other script order (e.g., analytics, third-party widgets).defer: For scripts that rely on the DOM being fully parsed, or depend on the execution order of other deferred scripts (e.g., UI interactivity, custom validations).- No attribute: Blocks rendering. Only use for critical scripts that must run before anything else.
ES Modules: Modern Scripting
ES Modules (ECMAScript Modules) provide a standardized system for organizing JavaScript code into separate files that can import and export functionalities.
When you use <script type="module">, the browser treats your script differently:
- Deferred by default: Modules are automatically deferred, meaning they don't block HTML parsing.
- Strict Mode: Modules run in strict mode by default.
- Scoped: Variables and functions declared at the top-level of a module are scoped to that module, not global.
How Modules Load
ES Modules use import to bring in functionality from other files and export to make functionality available.
The browser handles module loading efficiently, fetching dependencies in parallel and executing them in the correct order, after the HTML is parsed.
Here's a look at basic module syntax:
// Example: myUtils.js
export const PI = 3.14159;
export function multiply(a, b) {
return a * b;
}
// Example: main.js (loaded with <script type="module">)
import { PI, multiply } from './myUtils.js';
console.log("Module imported successfully.");
console.log("PI value:", PI);
console.log("5 * 10 =", multiply(5, 10));Script Loading Choices
You're building a website and need to load several JavaScript files. Which of the following statements about efficient script loading are TRUE?
Recap: Mastered Loading
Great job! You've learned how to load JavaScript efficiently:
- Default scripts block parsing, slowing down your page.
- The
asyncattribute allows scripts to download in parallel and execute immediately, ideal for independent scripts. - The
deferattribute also downloads in parallel but waits until the HTML is fully parsed before executing, maintaining order. - ES Modules (
<script type="module">) offer a modern, structured way to organize code, behaving like deferred scripts by default.
By applying these strategies, you can significantly improve your website's perceived and actual loading performance!
자주 묻는 질문
“효율적인 스크립트 로딩 전략” 강의는 무료인가요?
네 — “효율적인 스크립트 로딩 전략” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Performance Optimization & Lighthouse 강의 전체를 잠금 해제할 수 있습니다. Web Performance Optimization & Lighthouse 강의에는 총 4개의 강의가 포함되어 있습니다.
“효율적인 스크립트 로딩 전략”에서 뭘 배우나요?
JavaScript를 비동기적으로 로드하고 중요하지 않은 스크립트의 실행을 지연하며 모듈 패턴을 효과적으로 사용하는 기법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Web Performance Optimization & Lighthouse을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Performance Optimization & Lighthouse을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Performance Optimization & Lighthouse은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“효율적인 스크립트 로딩 전략” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Performance Optimization & Lighthouse 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Performance Optimization & Lighthouse 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- JavaScript 페이로드 최소화
- 효율적인 스크립트 로딩 전략
- 웹 워커와 메인 스레드 분리
- 코드 분할과 지연 로딩