What is the best way to load JS?


I was facing problems with loading JS, especially IE8, and I had this doubt. I researched a lot, I ended up improving some things.

Currently, I load all JS files at the bottom of the page, before the body tag.

    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="jquery.validate.min.js"></script>
    <script type="text/javascript" src="funcoes.js"></script>

In the case of funcoes.js is where I call (or would like to call) all functions of the site. And that's where problems happen. I have in it for example:


$(window).scroll(function () {



function validar(){

I do not know if you have any order in calling these functions ... I do not know, for example, when I have to use $(function(){...}); .

I always have to be testing, and sometimes it happens that in IE8 some function does not work, hence the novel of moving places (sometimes calling just below the scripts in body between the tags script solves), then this function works, but another one stops working, and then I'll start testing again ...

What can I be doing wrong?

asked by anonymous 10.04.2014 / 20:39

3 answers


You need to use a framework that manages file requests for you and does this only on demand, for example, the file with the validar() method will be loaded only if the method is actually called, thus always requesting of the files in the correct order.

Search for RequireJS: link

10.04.2014 / 21:49

Browsers when loading a page run it from top to bottom from right to left. When the browser goes through a javascript file it immediately executes the code of this but however if Javascript functions are making use of the HTML before the browser arrives and writes it gives error .

To our happiness, the browser triggers two events:

First - Tell us when a page has loaded all the HTML ( DOM Ready )

Second - Indicates when a page has uploaded all images. ( Window Load )

When you use functions that handle HTML, it's best to call them only when all HTML is already loaded DOM Ready

In the case of JQuery you should always start executing your Javascript on:

     //... etc

function Funcao1() {}
function Funcao2() {}
function Funcao3() {}
10.04.2014 / 22:54

Load the libraries between <head> e </head> . The content of the head is loaded before the body.

11.04.2014 / 03:11