Reputation: 1015
I have searched the web, found some answers but none of them work. All i want for my site to load faster. I have minified my images. Now am using jquery and used version hosted by google. Though it's not hosted on my site, it's the heaviest file (32kb) in the site and it loads 2nd on the line before any other images. I have tried the adding a javascript before the body closing tag like this:
<script language="javascript">
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
document.body.appendChild(e)
var f=document.createElement('script');
f.setAttribute('type','text/javascript');
f.setAttribute('src','myjs.js');
document.body.appendChild(f)
</script>
On firebug console, it shows that jquery is loaded last. However it also shows uncaught reference error $ not defined, which am guessing an error you get when jquery isn't loaded properly.
If i put these two js files inside the head tag, everything works fine.
How can I accomplish this task?
thanks.
Upvotes: 0
Views: 2424
Reputation: 1259
I was unable to force the script order in a particular system and I was able to get around the issue by wrapping my jQuery code with addEventListener
<script><!--
(function() {
'use strict';
window.addEventListener('load', function() {
// All resources loaded
$('#my-selector').on('click', function(event){
//Do something
});
}, false);
})();
//--></script>
Which allows me to load jQuery at the bottom of the document and still use '$' in my code further up in the DOM where needed. Not a perfect solution for all situations, but served my purposes ;)
Upvotes: 0
Reputation: 10668
Loading javascript files dynamically causes them to be loaded asynchronously, so you can't guarantee which library will load first. If you need to enforce order (as you always will with a library like jQuery), you'll need to add script
tags with src
attributes to page like so:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="myjs.js"></script>
If you add your script tags as the last elements in the body
element rather than the head
, it will give the appearance of loading faster (progressive enhancement).
EDIT As one of the commenters noted, you can read the answer to this question to get more detail.
Upvotes: 1