binarious
binarious

Reputation: 4588

Is it worth collecting jQuery-related scripts to run them at the end of the document?

I want to place jQuery just before the closing </body>-Tag like it's recommended. But because I'm using a Content Management System, inline scripts that require jQuery will be executed before the closing body tag.

My question now is: Is it worth to collect jQuery-based scripts in an array and run them at the end of the document when jQuery is loaded (EXAMPLE) OR just load jQuery in the head section?

Upvotes: 1

Views: 148

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

You could adopt the approach described here

the idea is to create a q global variable soon in the header and use a temporary window.$ function to collect all the code/functions/plugin jQuery dependent.

window.q=[];
window.$=function(f){
  q.push(f);
};

and after you load jQuery you will pass all the functions to the real $.ready function.

$.each(q,function(index,f){
  $(f)
});

in this way you will be able to safely include your jquery code before the jQuery lib inclusion

If this could be better than loading jQuery in the head it may depends on how much code you have to push into q temporary function.

jQuery placed into <head> section would require a single blocking script. But if you have much code to inject everywhere inside the document you may have a lot of huge blocking scripts that stop the rendering process.

On the contrary loading a lot of scripts after dom ready event it could easily make your page faster to load so this approach it's better and the benefits can be more evident.

So there's no a definitive answer valid for all code and all pages: even if this kind of technique anyway is generally good and preferable (because you have the benefit of a as-later-as-possible script execution), you should ever make some test with both the approaches and look at loading and rendering time. The article at the beginning has some consideration on the performance but also explains why stackoverflow didn't use it.

Upvotes: 4

GillesC
GillesC

Reputation: 10874

Just load jQuery in the head, it will be cached after the first load and won't slow down anything after that.

Everything else sounds like it would be over the top and I am not sure that the gain in performance will be that significant to justify the extra work.

Also sometime if your page load slowly with the javascript at the bottom it can take longer to come and load which means the visual without javascript might be visible and not provide such a good experience to the user.

Upvotes: 0

Related Questions