Evorlor Evorlor - 3 months ago 6
Javascript Question

How can I, and should I, load my .js files from a different file for cleanliness?

I have about 10

files that I am loading into
at the bottom of my
like so:

<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="assets/js/javascript1.js"></script>
<script src="assets/js/javascript2.js"></script>
<script src="assets/js/javascript3.js"></script>

Is there a way to move all of my javascript includes into a separate file for improved readability? If there is, should I do this, or are there reasons I want to keep them in the page in which they are used?

I am trying to do something along these lines, although this does not work:

At the bottom of my

<script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="assets/js/javascript-loader.js"></script>

Then in



The $.getScript(...) jQuery method is asynchronous, and therefore it will not retrieve your scripts consequently, resulting in the scripts being loaded in a random order (e.g. "script3" gets loaded before "script1"): so if any code in some of them relies on previous scripts there's a high chance that it may go completely wrong and fail rising some TypeError for undefined variables.

To make sure your scripts load in the correct order you can make synchronous Ajax calls, like this:

function loadScript(url) {
    var x = new XMLHttpRequest(),
        s = document.createElement('script');

    x.open('GET', url);

    s.textContent = x.responseText;

// ...

but this will obviously slow down your page a lot, freezing it until all the scripts are loaded. By the way there are some good libraries (e.g. RequireJS which relies on jQuery) to load scripts asynchronously in your page at any time, even though IMHO I wouldn't feel very good about using them.

To answer your question: if you don't want to use external libraries (with dependencies) it's better to keep the scripts in the body of your document: it makes them load faster and doesn't require additional effort.