Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scripts: async, defer, Bezier curve#356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
sahinyanlik merged 3 commits intojavascript-tutorial:masterfromcys27:master
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 70 additions & 70 deletions2-ui/5-loading/02-script-async-defer/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,152 +1,152 @@

# Scripts: async, defer
#Komut Dosyaları (Scripts): async, defer

In modern websites, scripts are often "heavier" than HTML: their download size is larger, and processing time is also longer.
Modern websitelerinde, genellikle script'ler HTML'den daha baskındır: script'lerin dosya/indirme boyutları büyüktür ve işlenme süreleri uzundur.

When the browser loadsHTML and comes across a`<script>...</script>`tag, it can't continue building DOM. It must execute thescript right now. The same happens for external scripts`<script src="..."></script>`: the browser must wait until thescriptdownloads, execute it, and only after process the rest of the page.
Tarayıcı,HTML'i yüklerken`<script>...</script>`etiketiyle karşılaştığında, DOM'u oluşturmaya devam edemez. Böyle bir durumdascript'i çalıştırmak zorundadır. Benzer durum`<script src="..."></script>` şeklinde dışarıdan aktarılan script'ler içinde geçerlidir: Tarayıcıscriptindirilene kadar bekleyecek, sonrasında onu çalıştıracak ve en sonunda sayfanın geri kalananı işleyecektir.

That leads to two important issues:
Bu durum iki önemli soruna yol açar:

1.Scripts can't seeDOMelements below them, so can't addhandlers etc.
2.If there's a bulkyscriptat the top of the page, it "blocks the page".Users can't see the page content till it downloads and runs:
1.Script'ler, onların altındakiDOMöğelerini (element) göremeyebilir, yani işleyici fonksiyonlar (handlers) vb. ekleyemezsiniz.
2.Sayfanın üst kısmında büyük birscriptvarsa, bu "sayfanın yüklenmesini engeller".Kullanıcılar, script indirilip, çalıştırılana kadar sayfa içeriğini göremez.

```html run height=100
<p>...content before script...</p>
<p>...script'ten önceki içerik...</p>

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

<!--This isn't visible until the script loads -->
<p>...content after script...</p>
<!--Bu, script yüklenene kadar gözükmeyecek -->
<p>...script'ten sonraki içerik...</p>
```

There are some workarounds to that. For instance, we can put ascript at the bottom of the page. Then it can see elements above it, and it doesn't block the page content from showing:
Bunun içi bazı geçici çözümler vardır. Örneğin,script'i sayfanın alt kısmına yerleştirebiliriz. Bu sayede script, kendinden önce bulunan öğeleri görebilir ve sayfa içeriğinin görüntülenmesini engellemez:

```html
<body>
...all content is above thescript...
...tüm içerikscript'in üzerindedir...

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

But this solution is far from perfect. For example, the browser notices thescript (and can start downloading it) only after it downloaded the full HTML document. For longHTMLdocuments, that may be a noticeable delay.
Fakat bu çözüm mükemmel olmaktan uzaktır. Örneğin, tarayıcı,script'i HTML belgesinin tamamını indirdikten sonra farkeder (ve onu indirmeye başlayabilir). UzunHTMLbelgelesi için, bu fark edilebilir bir gecikme olabilir.

Such things are invisible for people using very fast connections, but many people in the world still have slower internetspeeds and use far-from-perfect mobile internet.
Bu tür durumlar çok hızlı bir internet bağlantısına sahip olanlar için önemsizdir, fakat dünyada birçok insan hala yavaş bir internethızına sahip ve mükemmel olmaktan uzak olan mobil interneti kullanıyor.

Luckily, there are two`<script>`attributes that solve the problem for us: `defer`and `async`.
Neyse ki, bizim için bu sorunu çözen iki tane`<script>`niteliği (attribute) vardır: `defer`ve `async`.

## defer

The`defer`attribute tells the browser that it should go on working with the page, and load thescript "inbackground", then run thescript when it loads.
`defer`niteliği, tarayıcıya sayfayı yüklemeye devam etmesini, vescript'in"arkaplanda" yüklemesini, sonrasında sayfa yüklendikten sonrascript'in çalıştırılmasını söyler.

Here's the same example as above, but with `defer`:
Yukarıdaki ile aynı örnek, fakat burada `defer` niteliği mevcut:

```html run height=100
<p>...content before script...</p>
<p>...script'lerden önceki içerik...</p>

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

<!--visible immediately -->
<p>...content after script...</p>
<!--hemen görülebilir -->
<p>...script'lerden sonraki içerik...</p>
```

-Scripts with`defer`never block the page.
-Scripts with`defer`always execute when the DOMis ready, but before`DOMContentLoaded` event.
- `defer`kullanılan script, sayfayı engellemez.
- `defer`kullanılan script, her zaman DOMhazır olduğunda,`DOMContentLoaded`olayından (event) önce çalıştırılır.

The following example demonstrates that:
Aşağıdaki örnek bunu göstermektedir:

```html run height=100
<p>...content before scripts...</p>
<p>...script'lerden önceki içerik...</p>

<script>
document.addEventListener('DOMContentLoaded', () => alert("DOMready afterdefer!")); // (2)
document.addEventListener('DOMContentLoaded', () => alert("DOMertelemeden (defer) sonra hazır!")); // (2)
</script>

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

<p>...content after scripts...</p>
<p>...script'lerden sonraki içerik...</p>
```

1.The page content shows up immediately.
2. `DOMContentLoaded` waits for thedeferred script. It only triggers when thescript `(2)`is downloaded is executed.
1.Sayfa içeriği hemen görünür.
2. `DOMContentLoaded`, ertelenmiş (deferred) script'i bekler. Sadecescript `(2)`indirilip, çalıştırıldığında tetiklenir.

Deferred scripts keep their relative order, just like regular scripts.
Ertelenmiş script'ler (deferred scripts), tıpkı normal script'ler gibi göreli sıralarını korurlar.

So, if we have a longscript first, and then a smaller one, then the latter one waits.
Yani, ilk olarak büyük birscript'e ve sonrasında küçük bir tanesine sahipsek, sonuncusu bekler.

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

```smart header="The small script downloads first, runs second"
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.
```smart header="Küçük komut dosyası önce indirilir, sonra çalıştırılır."
Tarayıcılar, performansı artırmak için sayfadaki komut dosyalarını tarar ve paralel/eş zamanlı olarak indirmeye başlar. Yani yukarıdaki örnekte her iki komut dosyasıda eş zamanlı olarak indirilir. Muhtemelen `small.js`ilk önce indirilecektir.

But the specification requires scripts to execute in the document order, so it waits for`long.js`to execute.
Ancak komut dosyalarının sayfadaki sıraya göre çalıştırılması gerekir, bu nedenle`long.js`çalıştırılmasını bekler.
```

```smart header="The`defer`attribute is only for external scripts"
The `defer` attribute is ignored if the `<script>`tag has no `src`.
```smart header="`defer`niteliği yalnızca dışarıdan aktarılan komut dosyaları içindir"
Eğer `<script>`etiketinde `src` yoksa `defer` niteliği yok sayılır.
```


## async

The`async`attribute means that a script is completely independent:
`async`niteliği, bir script'in tamamiyle bağımsız olduğu anlamına gelir:

-The page doesn't wait forasync scripts, the contents is processed and displayed.
- `DOMContentLoaded`and async scripts don't wait each other:
- `DOMContentLoaded`may happen both before anasync script (if an asyncscriptfinishes loading after the page is complete)
- ...or after an async script (if an asyncscriptis short or was in HTTP-cache)
-Other scripts don't wait for`async`scripts, and`async`scripts don't wait for them.
-Sayfa asenkron script'leri (async scripts) beklemez, içerik işlenir ve görüntülenir.
- `DOMContentLoaded`ve asenkron script'ler (async scripts) birbirlerini beklemezler:
- `DOMContentLoaded`ya bir asenkron script'ten (async script) önce gerçekleşebilir (bir asenkronscriptsayfa tamamlandıktan sonra yüklemeyi bitirirse)
- ...ya da bir asenkron script'ten sonra (bir asenkronscriptküçük ya da HTTP önbelleğinde mevcut ise)
-Diğer script'ler,`async`script'leri için,`async`script'leri de onlar için beklemez.


So, if we have several`async`scripts, they may execute in any order. Whatever loads first -- runs first:
Dolasıyla, birden fazla`async`script'imiz varsa, onlar herhangi bir sırada çalıştırılır. İlk önce hangisi yüklenirse o çalıştırılır:

```html run height=100
<p>...content before scripts...</p>
<p>...script'lerden önceki içerik...</p>

<script>
document.addEventListener('DOMContentLoaded', () => alert("DOMready!"));
document.addEventListener('DOMContentLoaded', () => alert("DOMhazır!"));
</script>

<script async src="https://javascript.info/article/script-async-defer/long.js"></script>
<script async src="https://javascript.info/article/script-async-defer/small.js"></script>

<p>...content after scripts...</p>
<p>...script'lerden sonraki içerik...</p>
```

1.The page content shows up immediately: `async`doesn't block it.
2. `DOMContentLoaded` may happen both before and after`async`, no guarantees here.
3.Async scripts don't wait for each other. A smallerscript `small.js`goes second, but probably loads before`long.js`, so runs first. That's called a "load-first" order.
1.Sayfa içeriği hemen görünür: `async`sayfayı engellemez.
2. `DOMContentLoaded`,`async`'den öncede gerçekleşebilir, sonrada gerçekleşebilir. Burada garanti yok.
3.Asenkron script'ler birbirlerini beklemezler. Küçükscript `small.js`ikinci sıradadır, fakat muhtemelen`long.js`'den önce yüklenecektir, dolayısıyla önce o çalıştırılacaktır. Buna "ilk sıradakini yükle" denir.

Async scripts are great when we integrate an independent third-partyscript into the page: counters, ads and so on, as they don't depend on our scripts, and our scripts shouldn't wait for them:
Asenkron script'ler, bağımsız bir üçüncü tarafscript'i sayfaya eklediğimizde harikadır: sayaçlar, reklamlar vb. bizim script'lerimize bağlı olmadıkları için komut dosyalarımız onları beklememelidir.

```html
<!-- Google Analyticsis usually added like this -->
<!-- Google Analyticsgenellikle bu şekilde eklenir -->
<script async src="https://google-analytics.com/analytics.js"></script>
```


## Dynamicscripts
##Dinamik Komut Dosyaları (DynamicScripts)

We can also add ascriptdynamically using JavaScript:
Ayrıca, JavaScript kullanarak dinamik olarak birscriptekleyebiliriz:

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

The script starts loading as soon as it's appended to the document`(*)`.
Script`(*)`, belgeye eklenir eklenmez yüklenmeye başlar.

**Dynamic scripts behave as "async"by default.**
**Dinamik scriptler varsayılan olarak "async"gibi davranır..**

That is:
-They don't wait for anything, nothing waits for them.
-Thescript that loads first -- runs first ("load-first" order).
Yani:
-Onlar herhangi bir şeyi beklemezler, hiçbir şeyde onları beklemez.
-İlk yüklenenscript, önce çalıştırılır ("ilk sıradakini yükle")

We can change the load-first order into the document order (just like regular scripts) by explicitly setting `async` property to `false`:
`async` özelliğini `false` olarak ayarlarsak, yükleme sırasını belge sırası olacak şekilde değiştirebiliriz:

```js run
let script = document.createElement('script');
Expand All@@ -159,7 +159,7 @@ script.async = false;
document.body.append(script);
```

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 thatflagthe order is "as in the document":
Örneğin, burada iki adet script ekledik.`script.async=false`olmadığından ilk sıradakini yükleye göre çalıştırılacaktı (muhtemelen `small.js`önce çalışacaktı).Fakat buflagsayesinde sıra "belgedeki sıra gibi" olur.


```js run
Expand All@@ -170,29 +170,29 @@ function loadScript(src) {
document.body.append(script);
}

// long.js runs first because of async=false
// long.js, async=false olduğundan dolayı önce çalıştırılır.
loadScript("/article/script-async-defer/long.js");
loadScript("/article/script-async-defer/small.js");
```


##Summary
##Özet

Both`async`and `defer`have one common thing: they don't block page rendering. So the user can read page content and get acquanted with the page immediately.
`async`ve `defer`niteliklerinin ortak bir özelliği vardır: sayfanın yüklenmesini (render) engellemezler. Böylece kullanıcı sayfa içeriğini okuyabilir ve sayfayla hemen etkileşime geçebilir.

But there are also essential differences between them:
Ancak aralarında temel farklılıklar vardır:

| |Order | `DOMContentLoaded` |
| |Sıra | `DOMContentLoaded` |
|---------|---------|---------|
| `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.|
| `defer` | *Document order* (as they go in the document). |Execute after the document is loaded and parsed (they wait if needed), right before `DOMContentLoaded`. |
| `async` | *İlk sırayı yükle*.Belgedeki sıraları önemleri değildir--hangisi önce yüklenirse |Alakasız. Henüz belgenin tamamı indirilmemişken yüklenebilir ve çalıştırılabilir. Bu durum, eğer scriptler küçük veya önbellekte mevcut ise ve belge yeterince uzun ise gerçekleşir.|
| `defer` | *Belge sırası* (belgeye girdikleri gibi). |Belge yüklenip, çözümlendendikten sonra (gerekirse beklerler), `DOMContentLoaded` olayından (event) hemen önce çalıştırılır. |

```warn header="Page without scripts should be usable"
Please note that if you're using`defer`, then the page is visible *before* the script loads.
```warn header="Sayfa, scriptler olmadan kullanılabilir olmalıdır."
`defer` kullanıyorsanız, lütfen sayfanın script yüklenmeden *önce* görüntüleneceğini unutmayın.

So the user may read the page, but some graphical components are probably not ready yet.
Yani kullanıcılar sayfayı okuyabilir, fakat bazı grafiksel bileşenler muhtemelen henüz hazır değildir.

There should be "loading" indication in proper places, not-working buttons disabled, to clearly show the user what's ready and what's not.
Kullanıcıya neyin hazır olup, neyin olmadığını göstermek için uygun yerlere "yükleniyor" ifadesi yerleştirilmeli, çalışmayan düğmeler (button) devre dışı bırakılmalıdır.
```

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.
Pratikte, `defer`tüm DOM'a ihtiyaç duyan ve/ya da göreli yürütme sırası önemli olan scriptler için kullanılır. Ve`async`sayaçlar, reklamlar gibi bağımsız scriptler için kullanılır. Ve onlarda sıra önemli değildir.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp