You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer.
4
+
모던 웹브라우저에서 돌아가는 스크립트들은 대부분 HTML보다 '무겁습니다'. 용량이 커서 다운로드받는 데 오랜 시간이 걸리고 처리하는 것 역시 마찬가지이죠.
5
5
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>`를 만났을 때도 마찬가지입니다. 외부에서 스크립트를 다운로드받고 실행한 후에야 나머지 페이지들을 처리할 수 있습니다.
7
7
8
-
That leads to two important issues:
8
+
이런 브라우저의 동작 방식은 두 가지 중요한 이슈를 만듭니다.
9
9
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.페이지 위쪽에 용량이 큰 스크립트가 있는 경우, 이 스크립트가 페이지를 '막아버립니다'. 페이지에 접속하는 사용자들은 스크립트를 다운받고 실행할 때까지 스크립트 아래쪽 페이지를 볼 수 없게 됩니다.
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
+
이런 부작용들을 피할 수 있는 몇 가지 방법이 있습니다. 아래 예시처럼 스크립트를 페이지 맨 아래 놓는 것이 하나의 방법이 될 수 있죠. 이렇게 하면 스크립트에서 스크립트 위에 있는 요소를 볼 수 있습니다. 또한, 페이지 콘텐츠 출력을 막지 않게 됩니다.
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 문서 전체를 다운로드 한 다음에 스크립트를 다운받게 하면 페이지가 정말 느려질 겁니다.
33
33
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
+
네트워크 속도가 빠른 곳에서 페이지에 접속하고 있다면 이런 지연은 눈에 잘 띄지 않습니다. 하지만 아직도 네트워크 환경이 열악한 곳이 많습니다. 모바일 네트워크 접속이 느린 곳도 많죠.
35
35
36
-
Luckily, there are two `<script>`attributes that solve the problem for us: `defer` and `async`.
36
+
다행히도 이런 문제를 해결할 수 있는 `<script>`속성이 있습니다. 바로 `defer`와 `async`입니다.
37
37
38
38
## defer
39
39
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 파싱이 멈추지 않는 이유는 여기에 있습니다.
41
41
42
-
Here's the same example as above, but with `defer`:
```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`보다 빨리 끝날 수 있습니다.
84
84
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` 다음에 실행됩니다.
86
86
```
87
87
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` 속성은 무시됩니다.
90
90
```
91
91
92
92
93
93
## async
94
94
95
-
The `async` attribute means that a script is completely independent:
95
+
`async` 속성은 스크립트가 완전히 독립적으로 행동할 수 있게 보장해 줍니다.
96
96
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` 스크립트 역시 다른 스크립트들을 기다리지 않습니다.
102
102
103
103
104
-
So, if we have several `async` scripts, they may execute in any order. Whatever loads first -- runs first:
104
+
이런 특징 때문에 페이지에 `async` 스크립트가 여러 개 있는 경우, 그 실행 순서가 제각각이 됩니다. 먼저 로드되는 스크립트가 먼저 실행됩니다.
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'라고 부릅니다.
122
122
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 스크립트는 개발 중인 스크립트에 의존하지 않고, 그 반대도 마찬가지이기 때문입니다.
124
124
125
125
```html
126
-
<!-- Google Analytics is usually added like this-->
We can also add a script dynamically using JavaScript:
133
+
자바스크립트를 사용하면 스크립트를 동적으로 추가할 수 있습니다(dynamic script).
134
134
135
135
```js run
136
136
let script =document.createElement('script');
137
137
script.src="/article/script-async-defer/long.js";
138
138
document.body.append(script); // (*)
139
139
```
140
140
141
-
The script starts loading as soon as it's appended to the document `(*)`.
141
+
이렇게 추가한 동적 스크립트는 문서에 추가되자 마자(`(*)`로 표시한 줄) 스크립트 로딩이 시작됩니다.
142
142
143
-
**Dynamic scripts behave as "async" by default.**
143
+
**동적 스크립트는 기본적으로 'async' 스크립트처럼 행동합니다.**
144
144
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').
148
148
149
149
150
150
```js run
@@ -158,7 +158,7 @@ script.async = false;
158
158
document.body.append(script);
159
159
```
160
160
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`가 있기 때문에 실행은 '문서에 추가된 순서'대로 됩니다.
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`스크립트는 다운로드 시 페이지 렌더링을 막지 않는다는 공통점이 있습니다. 따라서 사용자는 오래 기다리지 않고도 페이지 콘텐츠를 볼 수 있습니다.
181
181
182
-
But there are also essential differences between them:
182
+
두 스크립트의 차이점은 다음과 같습니다.
183
183
184
-
||Order|`DOMContentLoaded`|
184
+
||순서|`DOMContentLoaded`|
185
185
|---------|---------|---------|
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` 이벤트 발생 전에 실행됩니다. |
188
188
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`를 사용하게 되면 스크립트가 실행되기 *전* 에 페이지가 화면에 출력된다는 점에 항상 유의해야 합니다.
191
191
192
-
So the user may read the page, but some graphical components are probably not ready yet.
192
+
사용자는 그래픽 관련 컴포넌트들이 준비되지 않은 상태에서 화면을 보게 될 수 있죠.
193
193
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) 처리를 해줘야 하죠. 이렇게 해야 사용자에게 현재 어떤 것은 사용할 수 있는지, 어떤 것은 사용할 수 없는지를 알려줄 수 있습니다.
195
195
```
196
196
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`는 방문자 수 카운터나 광고 관련 스크립트같이 독립적인 스크립트에 혹은 실행 순서가 중요하지 않은 경우에 적용합니다.
0 commit comments