What is the difference of loading javascript in <script> or external file?

Asked

Viewed 670 times

3

What is the difference of loading javascript in or external file . js?

<script> Código aqui </script>
ou
<script src="caminho"> </script>

Is there a difference in performance? Loading? When to use one or the other?

  • When it says "external file . js" it means another domain’s url?

  • Not necessarily Sergio

2 answers

2

In terms of performance, there is, because the browser needs to request another (s) file(s). As for using one or the other, it’s a value judgment you need to make: will you care about performance (virtually, it’s not too big - it depends on the size of the other(s) files)? You want to leave it next to HTML?

I personally prefer to put in external files, except when it is something of a form or something of the type (inherent in the particularities of the page, not to keep creating a file for each form of my applications), for example.

1

As Guilherme said, when you point to a Javascript file the browser necessarily makes one more request on the server, whether in the same domain or not.

This incurs network latency, that is, a longer time until the page is ready if the same file is inserted in HTML.

But there is a use case for each approach; web optimization always suggests that you decrease the number of requests to the maximum and that does not mean sticking everything in the middle of HTML but rather that in a build step of your project you concatenate all the files. js in just one or that you concaten them in a way that makes more sense for your application, the important thing is to reduce the amount of requests and make it clear that have 139 requests to upload files. js is not healthy.

One of the disadvantages of having JS inserted in the middle of HTML is that it is very difficult to apply processing steps such as minification, compression, concatenation, etc, before making your project available in production.

On the other hand it might make sense to have JS in a script tag, for example; the application I work with is quite heavy (~2MB Javascript), if the user entered the site and had to wait for the ~2MB to download until he knew that the page did not lock probably the default index of viewing the page would be very high, so what we do isinsert the jQuery code in the middle of the HTML so that the user opens the page Jquery is already loaded and ready to display a progress bar plugin that indicates the loading of these ~2MB.

The extraction of the code. JS in separate files also facilitates modularization, ie if you need the same code on another page it’s just a matter of importing it again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.