动态加载JQuery文件并执行它

时间:2013-05-22 21:18:21

标签: javascript jquery

我必须动态加载JQuery脚本,因为脚本有时是收费的,有时却不收费。之后,我必须执行一个JQuery函数。我试过但它不起作用。你能帮助我吗?这是我的代码:

<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>

1 个答案:

答案 0 :(得分:0)

试试这个:

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);
}

然后只需:loadScript("http://code.jquery.com/jquery-1.7.1.min.js", myCode);

来源:How do I include a JavaScript file in another JavaScript file?