Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should all JavaScript code be placed in the head with HeadJS?

I am using HeadJS to load all my JavaScript code in the head of my website. Should I be doing the following, loading all my JavaScript in the head with HeadJS?

<script src="/-/js/head.js"></script>

<script>
    head.js("https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js")
        .js("/-/js/slideshow.js")
        .js("/-/js/modernizr.js")
        .js("/-/js/cookie.js")
        .js("/-/js/thumbs.js")
        .js("/-/js/infinitescroll.js")
        .js("/-/js/manual-trigger.js")
        .js("/-/js/easing.js")
        .js("/-/js/thumbs.js")
        .js("/-/js/popup.js")
        .js("/-/js/sharre.js")
        .js("/-/js/selectivizr.js")
        .js("/-/js/scripts.js");
</script>

Also, the file 'scripts.js' is all my own jQuery scripting, which uses other JavaScript scripts in the head. Is this the best way to run this for optimisation?

I use to wrap all the code in this file:

head.ready(function() { my code });
like image 290
ccdavies Avatar asked Jul 10 '26 10:07

ccdavies


1 Answers

Correct practice is to download resources in parallel so that no one asset blocks the downloading of other assets, such as scripts that block the rendering of content. Ideally you should download CSS first and then, in parallel, scripts in order of importance/dependency. For example, you will want to download your jQuery code before jQuery related scripts, and you will want to download your functionality before your "decorative" scripts.

Again, it is immaterial when they start to download, so long as they do not block other assets (that is, CSS and content).

At the OP, from my quick study, your approach does seem correct. From what I have read, headjs can download in parallel, but execute in order (you can specify the order). The approach you have used will execute whichever script arrives first. You are very adventurous! ^_^

Unfortunately I do not know the functional importance of each of your scripts, but I would suggest reordering, something like:

<script>
head.js("https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js",
    "/-/js/modernizr.js",
    "/-/js/selectivizr.js",
    "/-/js/cookie.js",
    etc...
    );
</script>

This will download scripts in parallel, but execute in this order. You are required to separate each script with a , to use the "download in parallel, execute in order" approach.

I THINK: Still investigating - You also have the option to include conditional downloads using:

head.browser.ie(insert scripts);

Check out the awesomeness.

When I saw the conditional load for Internet Explorer (nevermind anything else), I considered giving the developer my first born child.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!