Stop being the product.
Become the owner.
or
sign uplog in
buut=In 2024, is it better to use <script async ... > to load non-blocking scripts, or use a script loader?

The common pattern for loading non-blocking scripts (e.g. any analytics or third party widgets) seems to be:

```
var script = document.createElement('script');
script.async true;
script.src = 'https://example.com/script.js';
document.getElementsByTagName('head')0].appendChild(script);
```

Or similar. There are other exmaples using `insertBefore`, but you get the gist.

Even as far back as 2014, [Ilya Grigorik wrote https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/ hat these script loaders could just be replaced with:

```
<script async src="https://example.com/script.js"></script>
```

In fact, he mentions that this new approach is not only shorter, but reduces load time, because it isn't blocked by the CSSOM.

But even today, Google Tag Manager, Facebook Pixel, and any other snippet I'm asked to embed uses the first approach. Throwing it out to the group: any ideas why?

Is it just that these services are designed to work across all devices, even as far back as IE 8 (that would explain the `var`), so they're covering their bases. Or do you think that developers are just copying each other? Or is there another reason? Do these scripts need the CSSOM to be ready before they can execute, for example?

The reason for asking: I was asked to add yet another tracking tool to a website, and seeing the same boilerplate code show up again and again just got me thinking about the Ilya Grigorik article.

---

Updates:

I probably should have used the term "script injection" instead of "script loading"

It turns out Adobe Analytics suggests https://experienceleague.adobe.com/en/docs/experience-platform/web-sdk/install/library#adding-the-code sing an inline `<script async src="..." />` tag.

Also, even though in my Google Tag Manger console, the snippet I'm given uses the script injection method, other documentation https://developers.google.com/tag-platform/gtagjs#add_the_google_tag_to_your_website ses the inline `script` tag too.

So maybe there's a degree of cargo cultism going on, and it's more than safe to use inline scripts going forward.

Although, obviously, if you want to load a script conditionally, e.g. ased on cookies, you have to use the script injection method.
#programming #technology #dev #js
source
earnings
4,000 mlx total
$0  total
engagement
6 views
0 reactions
reaction stream
0 comments