0

I have to load JQuery script dynamically beacause the script is sometimes charged and sometimes it doesn't. After that, I have to execute a JQuery function. I have tried but it doesn't work. Can you help me? This is my code:

<script>
    var script   = document.createElement("script");`
    script.type  = "text/javascript";
    script.src   = "http://code.jquery.com/jquery-1.7.1.min.js";    
    script.text  = "alert('voila!');"               
    document.body.appendChild(script);
    $(document).ready(function() {                                         
    getNumRecommendations("http://localhost:8080/elAbogado/","3974");});
</script>
Farid Rn
  • 3,167
  • 5
  • 39
  • 66
  • You have to wait for the script to be loaded before using `$` – Kevin B May 22 '13 at 21:19
  • Note: You're trying to give a `script` element both a `src` *and* content (via `text`). You can't do that, a `script` element can have one **or** the other, never both. – T.J. Crowder May 22 '13 at 21:21
  • 1
    *"I have to load dinamically the JQuery script beacause the script is sometimes charged and sometimes it doesn't."* Huh? – T.J. Crowder May 22 '13 at 21:23

1 Answers1

0

Try this:

function loadScript(url, callback)
{
    // adding the script tag to the head as suggested before
   var head = document.getElementsByTagName('head')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function 
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback;

   // fire the loading
   head.appendChild(script);
}

And then just: loadScript("http://code.jquery.com/jquery-1.7.1.min.js", myCode);

Source: How do I include a JavaScript file in another JavaScript file?

Community
  • 1
  • 1