Chobeat
Chobeat

Reputation: 3535

Dynamically load jquery

I'm working in a really twisted environment in which I cannot handle this problem through the view logic of the MVC framework I'm using (Cakephp). It could happen because I have to load this piece of code inside a page which already has a jQuery script loaded in.

If I simply load jQuery in my piece of code, it works as long as there's no other jQuery scripts present. When there are 2 scripts, it doesn't work and says $ is not a function. Not really sure how this works but explanations could help.

Anyway I've got to the point of dynamically loading the script into the page.

So this is my code:

<script id="loadjq" type="text/javascript"></script>
<script id="loadcloud" type="text/javascript"></script>
<script type="text/javascript">
if(typeof jQuery=="undefined"){
    document.getElementById('loadjq').src= 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
}
document.getElementById('loadcloud').src= '/js/jqcloud.js';
$(document).ready(function(){
    $("#tagcloud").jQCloud(word_list,{});
});
</script>

This loads the script but when I try to load jqcloud.js, it can't find the other script, probably because it runs before the other script is loaded. With a few dirty tricks I could go through that, but the same problem happens when i reach $(document).ready(function()

Is there a clean way to do this? I need it to wait for the previous scripts to be loaded before executing, or at least, that's what the problem looks like. Not really sure if this is really my problem.

Upvotes: 4

Views: 1218

Answers (1)

AlexC
AlexC

Reputation: 10756

How about setting event handlers on the jquery script element to call the jqcloud script on load completion. Something like

if(typeof jQuery=="undefined"){
   var loadjqScript = document.getElementById('loadjq').src =
                'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js';
        // Code below handles browser that support script onload 
        // and ones that don't
   var loadFunction = function()  
   {  
      if (this.readyState == 'complete' || this.readyState == 'loaded') {  
           loadJqCloud();   
      }  
   };  
   loadjqScript.onreadystatechange = loadFunction;

   loadjqScript.onload = loadJqCloud;  
}

function loadJqCloud() {
    document.getElementById('loadcloud').src= '/js/jqcloud.js'
 }

Upvotes: 4

Related Questions