Skip to content

Commit 5d7dc9e

Browse files
[비동기, 지연 스크립트] 번역
1 parent e9b4cb5 commit 5d7dc9e

File tree

3 files changed

+71
-71
lines changed

3 files changed

+71
-71
lines changed
Lines changed: 69 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,150 +1,150 @@
11

2-
# Scripts: async, defer
2+
# 비동기, 지연 스크립트
33

4-
In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer.
4+
모던 웹브라우저에서 돌아가는 스크립트들은 대부분 HTML보다 '무겁습니다'. 용량이 커서 다운로드받는 데 오랜 시간이 걸리고 처리하는 것 역시 마찬가지이죠.
55

6-
When the browser loads HTML and comes across a `<script>...</script>` tag, it can't continue building the DOM. It must execute the script right now. The same happens for external scripts `<script src="..."></script>`: the browser must wait until the script downloads, execute it, and only after process the rest of the page.
6+
브라우저는 HTML을 읽다가 `<script>...</script>` 태그를 만나면 스크립트를 먼저 실행해야 하므로 DOM 생성을 멈춥니다. 이는 외부 스크립트 `<script src="..."></script>`를 만났을 때도 마찬가지입니다. 외부에서 스크립트를 다운로드받고 실행한 후에야 나머지 페이지들을 처리할 수 있습니다.
77

8-
That leads to two important issues:
8+
이런 브라우저의 동작 방식은 두 가지 중요한 이슈를 만듭니다.
99

10-
1. Scripts can't see DOM elements below them, so they can't add handlers etc.
11-
2. If there's a bulky script at the top of the page, it "blocks the page". Users can't see the page content till it downloads and runs:
10+
1. 스크립트는 스크립트 아래에 있는 DOM 요소를 볼 수 없습니다. 따라서 핸들러 추가 같은 여러 행위가 불가능해집니다.
11+
2. 페이지 위쪽에 용량이 큰 스크립트가 있는 경우, 이 스크립트가 페이지를 '막아버립니다'. 페이지에 접속하는 사용자들은 스크립트를 다운받고 실행할 때까지 스크립트 아래쪽 페이지를 볼 수 없게 됩니다.
1212

1313
```html run height=100
14-
<p>...content before script...</p>
14+
<p>...스크립트 앞 콘텐츠...</p>
1515

1616
<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
1717

18-
<!-- This isn't visible until the script loads -->
19-
<p>...content after script...</p>
18+
<!-- 스크립트 로딩이 끝나기 전까지 아래 내용이 보이지 않습니다. -->
19+
<p>...스크립트 뒤 콘텐츠...</p>
2020
```
2121

22-
There are some workarounds to that. For instance, we can put a script at the bottom of the page. Then it can see elements above it, and it doesn't block the page content from showing:
22+
이런 부작용들을 피할 수 있는 몇 가지 방법이 있습니다. 아래 예시처럼 스크립트를 페이지 맨 아래 놓는 것이 하나의 방법이 될 수 있죠. 이렇게 하면 스크립트에서 스크립트 위에 있는 요소를 볼 수 있습니다. 또한, 페이지 콘텐츠 출력을 막지 않게 됩니다.
2323

2424
```html
2525
<body>
26-
...all content is above the script...
26+
... 스크립트 위 콘텐츠들 ...
2727

2828
<script src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
2929
</body>
3030
```
3131

32-
But this solution is far from perfect. For example, the browser notices the script (and can start downloading it) only after it downloaded the full HTML document. For long HTML documents, that may be a noticeable delay.
32+
그런데 이 방법은 완벽한 해결책은 아닙니다. HTML 문서 자체가 아주 큰 경우를 가정해봅시다. 브라우저가 HTML 문서 전체를 다운로드 한 다음에 스크립트를 다운받게 하면 페이지가 정말 느려질 겁니다.
3333

34-
Such things are invisible for people using very fast connections, but many people in the world still have slow internet speeds and use a far-from-perfect mobile internet connection.
34+
네트워크 속도가 빠른 곳에서 페이지에 접속하고 있다면 이런 지연은 눈에 잘 띄지 않습니다. 하지만 아직도 네트워크 환경이 열악한 곳이 많습니다. 모바일 네트워크 접속이 느린 곳도 많죠.
3535

36-
Luckily, there are two `<script>` attributes that solve the problem for us: `defer` and `async`.
36+
다행히도 이런 문제를 해결할 수 있는 `<script>` 속성이 있습니다. 바로 `defer``async`입니다.
3737

3838
## defer
3939

40-
The `defer` attribute tells the browser that it should go on working with the page, and load the script "in background", then run the script when it loads.
40+
브라우저는 `defer` 속성이 있는 스크립트(이하 `defer` 스크립트 또는 지연 스크립트)를 '백그라운드'에서 불러옵니다. 실행은 페이지 로딩이 끝날 때까지 *지연* 되죠. `defer` 스크립트를 만나도 HTML 파싱이 멈추지 않는 이유는 여기에 있습니다.
4141

42-
Here's the same example as above, but with `defer`:
42+
위쪽 예시와 동일한 코드인데 스크립트에 `defer`만 붙여보겠습니다.
4343

4444
```html run height=100
45-
<p>...content before script...</p>
45+
<p>...스크립트 앞 콘텐츠...</p>
4646

4747
<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
4848

49-
<!-- visible immediately -->
50-
<p>...content after script...</p>
49+
<!-- 바로 볼 수 있네요! -->
50+
<p>...스크립트 뒤 콘텐츠...</p>
5151
```
5252

53-
- Scripts with `defer` never block the page.
54-
- Scripts with `defer` always execute when the DOM is ready, but before `DOMContentLoaded` event.
53+
- 지연 스크립트는 HTML 파싱을 절대 막지 않습니다.
54+
- 지연 스크립트는 DOM 트리가 완성된 후, `DOMContentLoaded` 이벤트가 발생하기 전에 실행됩니다.
5555

56-
The following example demonstrates that:
56+
예시를 통해 직접 살펴봅시다.
5757

5858
```html run height=100
59-
<p>...content before scripts...</p>
59+
<p>...스크립트 앞 콘텐츠...</p>
6060

6161
<script>
62-
document.addEventListener('DOMContentLoaded', () => alert("DOM ready after defer!")); // (2)
62+
document.addEventListener('DOMContentLoaded', () => alert("DOM이 준비되고 `defer` 스크립트가 실행된 후, DOMContentLoaded 이벤트가 발생했습니다!")); // (2)
6363
</script>
6464

6565
<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1"></script>
6666

67-
<p>...content after scripts...</p>
67+
<p>...스크립트 뒤 콘텐츠...</p>
6868
```
6969

70-
1. The page content shows up immediately.
71-
2. `DOMContentLoaded` waits for the deferred script. It only triggers when the script `(2)` is downloaded and executed.
70+
1. 페이지 콘텐츠는 바로 출력됩니다.
71+
2. `DOMContentLoaded` 이벤트는 지연 스크립트를 기다립니다. 따라서 `DOMContentLoaded` 이벤트는 DOM 트리가 완성되고 지연 스크립트가 실행된 후에 실행됩니다.
7272

73-
Deferred scripts keep their relative order, just like regular scripts.
73+
지연 스크립트도 일반 스크립트와 마찬가지로 HTML에 추가된 순(상대순, 요소순)으로 실행됩니다.
7474

75-
So, if we have a long script first, and then a smaller one, then the latter one waits.
75+
따라서 길이가 긴 스크립트가 앞에, 길이가 짧은 스크립트가 뒤에 있을 때, 뒤에 있는 스크립트는 앞의 스크립트가 실행될 때까지 대기합니다.
7676

7777
```html
7878
<script defer src="https://javascript.info/article/script-async-defer/long.js"></script>
7979
<script defer src="https://javascript.info/article/script-async-defer/small.js"></script>
8080
```
8181

82-
```smart header="The small script downloads first, runs second"
83-
Browsers scan the page for scripts and download them in parallel, to improve performance. So in the example above both scripts download in parallel. The `small.js` probably makes it first.
82+
```smart header="작은 스크립트는 먼저 다운되지만, 실행은 나중에 됩니다."
83+
브라우저는 성능을 위해 페이지에 어떤 스크립트들이 있는지 스캔한 다음 스크립트를 병렬적으로 다운로드합니다. 따라서 위 예시의 스크립트 다운도 병렬적으로 진행되죠. `small.js` 다운로드가 `long.js`보다 빨리 끝날 수 있습니다.
8484
85-
But the specification requires scripts to execute in the document order, so it waits for `long.js` to execute.
85+
그렇지만 명세서에서 스크립트를 문서에 추가된 순서대로 실행하라고 정의했기 때문에 `small.js`는 `long.js` 다음에 실행됩니다.
8686
```
8787

88-
```smart header="The `defer` attribute is only for external scripts"
89-
The `defer` attribute is ignored if the `<script>` tag has no `src`.
88+
```smart header="`defer` 속성은 외부 스크립트에만 유효합니다."
89+
`<script>``src`가 없으면 `defer` 속성은 무시됩니다.
9090
```
9191
9292
9393
## async
9494
95-
The `async` attribute means that a script is completely independent:
95+
`async` 속성은 스크립트가 완전히 독립적으로 행동할 수 있게 보장해 줍니다.
9696
97-
- The page doesn't wait for async scripts, the contents are processed and displayed.
98-
- `DOMContentLoaded` and async scripts don't wait for each other:
99-
- `DOMContentLoaded` may happen both before an async script (if an async script finishes loading after the page is complete)
100-
- ...or after an async script (if an async script is short or was in HTTP-cache)
101-
- Other scripts don't wait for `async` scripts, and `async` scripts don't wait for them.
97+
- 페이지는 `async` 속성이 붙은 스크립트(이하 async 스크립트 또는 비동기 스크립트)를 기다리지 않고 페이지 내 콘텐츠를 처리, 출력합니다.
98+
- `DOMContentLoaded`async 스크립트는 서로를 기다리지 않습니다.
99+
- 페이지 구성이 끝나기 전에 `async` 스크립트 로딩이 끝난 경우, `DOMContentLoaded`는 async 스크립트 전에 발생할 수 있습니다,
100+
- async 스크립트가 짧거나 HTTP 캐시 안에 있는 경우, `DOMContentLoaded`는 `async` 스크립트 후에도 발생할 수 있습니다.
101+
- 다른 스크립트들은 `async` 스크립트를 기다리지 않습니다. `async` 스크립트 역시 다른 스크립트들을 기다리지 않습니다.
102102
103103
104-
So, if we have several `async` scripts, they may execute in any order. Whatever loads first -- runs first:
104+
이런 특징 때문에 페이지에 `async` 스크립트가 여러 개 있는 경우, 그 실행 순서가 제각각이 됩니다. 먼저 로드되는 스크립트가 먼저 실행됩니다.
105105
106106
```html run height=100
107-
<p>...content before scripts...</p>
107+
<p>...스크립트 앞 콘텐츠...</p>
108108
109109
<script>
110-
document.addEventListener('DOMContentLoaded', () => alert("DOM ready!"));
110+
document.addEventListener('DOMContentLoaded', () => alert("DOM이 준비 되었습니다!"));
111111
</script>
112112
113113
<script async src="https://javascript.info/article/script-async-defer/long.js"></script>
114114
<script async src="https://javascript.info/article/script-async-defer/small.js"></script>
115115
116-
<p>...content after scripts...</p>
116+
<p>...스크립트 뒤 콘텐츠...</p>
117117
```
118118

119-
1. The page content shows up immediately: `async` doesn't block it.
120-
2. `DOMContentLoaded` may happen both before and after `async`, no guarantees here.
121-
3. Async scripts don't wait for each other. A smaller script `small.js` goes second, but probably loads before `long.js`, so runs first. That's called a "load-first" order.
119+
1. 페이지 콘텐츠는 바로 출력됩니다. 비동기 스크립트는 페이지 로딩을 막지 않습니다.
120+
2. `DOMContentLoaded` 이벤트는 비동기 스크립트 전이나 후에 실행됩니다. 순서에 보장이 없습니다.
121+
3. 비동기 스크립트는 서로를 기다리지 않습니다. 위치상으론 `small.js`가 아래이긴 하지만 `long.js`보다 먼저 로드되었기 때문에 더 먼저 실행되었습니다. 이를 'load-first order'라고 부릅니다.
122122

123-
Async scripts are great when we integrate an independent third-party script into the page: counters, ads and so on, as they don't depend on our scripts, and our scripts shouldn't wait for them:
123+
비동기 스크립트는 방문자 수 카운터나 광고 관련 스크립트같이 각각 독립적인 역할을 하는 서드 파티 스크립트를 현재 개발 중인 스크립트에 통합하려 할 때 아주 유용합니다. async 스크립트는 개발 중인 스크립트에 의존하지 않고, 그 반대도 마찬가지이기 때문입니다.
124124

125125
```html
126-
<!-- Google Analytics is usually added like this -->
126+
<!-- Google Analytics는 일반적으로 다음과 같이 삽입합니다. -->
127127
<script async src="https://google-analytics.com/analytics.js"></script>
128128
```
129129

130130

131-
## Dynamic scripts
131+
## 동적 스크립트
132132

133-
We can also add a script dynamically using JavaScript:
133+
자바스크립트를 사용하면 스크립트를 동적으로 추가할 수 있습니다(dynamic script).
134134

135135
```js run
136136
let script = document.createElement('script');
137137
script.src = "/article/script-async-defer/long.js";
138138
document.body.append(script); // (*)
139139
```
140140

141-
The script starts loading as soon as it's appended to the document `(*)`.
141+
이렇게 추가한 동적 스크립트는 문서에 추가되자 마자(`(*)`로 표시한 줄) 스크립트 로딩이 시작됩니다.
142142

143-
**Dynamic scripts behave as "async" by default.**
143+
**동적 스크립트는 기본적으로 'async' 스크립트처럼 행동합니다.**
144144

145-
That is:
146-
- They don't wait for anything, nothing waits for them.
147-
- The script that loads first -- runs first ("load-first" order).
145+
따라서, 동적 스크립트는 다음과 같은 특징을 갖습니다.
146+
- 그 어떤 것도 기다리지 않습니다. 다른 자원들도 동적 스크립트를 기다리지 않습니다.
147+
- 먼저 로드된 스크립트가 먼저 실행됩니다('load-first order').
148148

149149

150150
```js run
@@ -158,7 +158,7 @@ script.async = false;
158158
document.body.append(script);
159159
```
160160

161-
For example, here we add two scripts. Without `script.async=false` they would execute in load-first order (the `small.js` probably first). But with that flag the order is "as in the document":
161+
아래 예시에선 두 개의 스크립트를 동적으로 문서에 추가합니다. `script.async=false`가 없었다면 이 두 스크립트는 'load-first order'로 실행됩니다. 크기가 작은 `small.js`가 먼저 실행되겠죠. 하지만 `script.async=false`가 있기 때문에 실행은 '문서에 추가된 순서'대로 됩니다.
162162

163163

164164
```js run
@@ -169,29 +169,29 @@ function loadScript(src) {
169169
document.body.append(script);
170170
}
171171

172-
// long.js runs first because of async=false
172+
// async=false이기 때문에 long.js가 먼저 실행됩니다.
173173
loadScript("/article/script-async-defer/long.js");
174174
loadScript("/article/script-async-defer/small.js");
175175
```
176176

177177

178-
## Summary
178+
## 요약
179179

180-
Both `async` and `defer` have one common thing: downloading of such scripts doesn't block page rendering. So the user can read page content and get acquainted with the page immediately.
180+
`async``defer` 스크립트는 다운로드 시 페이지 렌더링을 막지 않는다는 공통점이 있습니다. 따라서 사용자는 오래 기다리지 않고도 페이지 콘텐츠를 볼 수 있습니다.
181181

182-
But there are also essential differences between them:
182+
두 스크립트의 차이점은 다음과 같습니다.
183183

184-
| | Order | `DOMContentLoaded` |
184+
| | 순서 | `DOMContentLoaded` |
185185
|---------|---------|---------|
186-
| `async` | *Load-first order*. Their document order doesn't matter -- which loads first | Irrelevant. May load and execute while the document has not yet been fully downloaded. That happens if scripts are small or cached, and the document is long enough. |
187-
| `defer` | *Document order* (as they go in the document). | Execute after the document is loaded and parsed (they wait if needed), right before `DOMContentLoaded`. |
186+
| `async` | *load-first order*. 문서 내 순서와 상관없이 먼저 로드된 스크립트가 먼저 실행됩니다. | 비동기 스크립트는 문서가 완전히 다운로드되지 않은 상태라도 로드 및 실행될 수 있습니다. 스크립트 크기가 작거나 캐싱 처리 되어있을 때 혹은 문서 길이가 아주 길 때 이런 일이 발생합니다. |
187+
| `defer` | *문서에 추가된 순* | 지연 스크립트는 문서 로드와 파싱이 완료된 후에, `DOMContentLoaded` 이벤트 발생 전에 실행됩니다. |
188188

189-
```warn header="Page without scripts should be usable"
190-
Please note that if you're using `defer`, then the page is visible *before* the script loads.
189+
```warn header="스크립트 로딩이 안 되었어도 페이지는 동작해야 합니다."
190+
`defer`를 사용하게 되면 스크립트가 실행되기 *전* 에 페이지가 화면에 출력된다는 점에 항상 유의해야 합니다.
191191
192-
So the user may read the page, but some graphical components are probably not ready yet.
192+
사용자는 그래픽 관련 컴포넌트들이 준비되지 않은 상태에서 화면을 보게 될 수 있죠.
193193
194-
There should be "loading" indications in the proper places, and disabled buttons should show as such, so the user can clearly see what's ready and what's not.
194+
따라서 지연 스크립트가 영향을 주는 영역엔 반드시 '로딩 인디케이터'가 있어야 합니다. 관련 버튼도 사용 불가(disabled) 처리를 해줘야 하죠. 이렇게 해야 사용자에게 현재 어떤 것은 사용할 수 있는지, 어떤 것은 사용할 수 없는지를 알려줄 수 있습니다.
195195
```
196196

197-
In practice, `defer` is used for scripts that need the whole DOM and/or their relative execution order is important. And `async` is used for independent scripts, like counters or ads. And their relative execution order does not matter.
197+
실무에선 `defer`DOM 전체가 필요한 스크립트나 실행 순서가 중요한 경우에 적용합니다. `async`는 방문자 수 카운터나 광고 관련 스크립트같이 독립적인 스크립트에 혹은 실행 순서가 중요하지 않은 경우에 적용합니다.

2-ui/5-loading/02-script-async-defer/long.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,4 @@
2929
// ...long js... ...long js... ...long js... ...long js... ...long js... ...long js...
3030
// ...long js... ...long js... ...long js... ...long js... ...long js... ...long js...
3131

32-
alert("Long script loaded");
32+
alert("사이즈가 큰 스크립트 로딩이 끝났습니다.");
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
// ...small js...
22

3-
alert("Small script loaded");
3+
alert("사이즈가 작은 스크립트 로딩이 끝났습니다.");

0 commit comments

Comments
 (0)