What's the difference of loading javascript into script or external file?

3

What's the difference of loading javascript into or external .js file?

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

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

    
asked by anonymous 26.11.2014 / 17:01

2 answers

2

In performance issue, there is, because the browser needs to make requests to other file (s). As for using one or the other, it's a judgment of value you have to make: you're going to care about the performance (virtually, not too big - depends on the size of the other files)? Do 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 (inherent in the particularities of the page, not to be creating a file for each form of my applications), for example.

    
26.11.2014 / 17:04
1

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

This results in network latency, ie 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 minimize the number of requests and that does not mean you have to stuff everything in the middle of HTML but rather that in a build step of your project you concatenate all .js files in only one or that you concatenate in a way that makes more sense to your application, the important thing is to reduce the amount of requests and make it clear that having 139 requests to load .js files 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 for production.

On the other hand it might rather make sense to have JS in a script tag, for example; the application I work on is very heavy (2MB of JavaScript), if the user entered the site and had to wait ~ 2MB to download until the page probably did not catch the page view rendering index would be very high, then the we do pre-insert the jQuery code in the middle of the HTML in this way as soon as the user opens the page JQuery is already loaded and ready to display a progress bar plugin that indicates the loading of those ~ 2MB. Extracting .JS code into separate files also makes it easy to modularize, so if you need the same code on another page it's just a matter of importing it again.

    
26.11.2014 / 17:39