I have a web application that loads several JavaScript files as follows (simplified, I actually have 8-10 files):
<script src="codigo1.js"></script>
<script src="codigo2.js"></script>
<script src="codigo3.js"></script>
<script src="codigo4.js"></script>
Some of those files are very large and take time to load, so I was thinking of using defer
o async
so they wouldn't affect the page load in general. But I run into a problem: some of those files are dependent on the load of the others.
For example, code4.js uses information that is loaded into code1.js and code2.js. But code1.js is a much larger file than code4.js, so if I load the scripts asynchronously it could be the case that code4.js is executed before code1.js.
Is there a way to use defer
or async
but keeping the order of execution indicated in the code? What alternatives do I have?
Use
defer
:Free translation of the specification :
Then, as explained in point 15 (simplified translation)
This means that the scripts with
defer
are executed after loading and parsing the page and in the order they are found in the DOM which solves your dependency problem.Think of this as a queue
<script>
that is executed when the html is done parsing.First of all, it is important that you add encoding
UTF-8
to the javascript files. This is so that it supports accent marks,á
é
í
ó
ú
for example, instead ofcodigo
, it will becódigo
.The following fixes the problem of scripts depending on others. The idea is that the files that depend on another are not added to the
html
, but another file must be added to the list of scripts.For example, here the is not loaded
codigo2.js
, it only loads thecodigo1.js
, and also theesperador.js
, which must be at the beginning, will take care of loading the first one.What it does is wait half a second for it to load a variable from the first file,
codigo1.js
that variable has to be previously declared, in my case it is calledvariable_código1_js
.File content
esperador.js
.You have already been given answers, however I offer you the alternative of using the amazing require.js library. Choose when to upload your files, instead of uploading them all at once.
Avoid writing so many tags
<script>
in the html document, that's not professional at all. Program in a modular and organized way. Everything in its proper place and at its proper time.It's just my humble opinion and recommendation. More information here .