Include a JS file using jQuery

11,076

Solution 1

Have you considered:

$('<script />', { type : 'text/javascript', src : addon}).appendTo('head');

This avoids having to manually escape the </script> closing tag.

Solution 2

You MUST escape the end tag <\/script> otherwise you close the scripts prematurely

Solution 3

try $.holdReady(true); $.getScript("sample.js", function() { $.holdReady(false); });

This ensures that your js is fully loaded before the onready object is fired and thus you can be sure that any objects/functions of the dynamically included js are available.

Solution 4

try

$.when(
    $.getScript( "sample.js" ),
    $.getScript( "simple.js" ),
    $.getScript( "jquery.js" ),
    $.Deferred(function( deferred ){
    $( deferred.resolve );
    })
    ).done(function(){
        //place your code here, the scripts are all loaded
});
Share:
11,076
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I actually have a problem with including JS file using jQuery. I found many sources but no one work with me. I'm pretty sure that the path of the js file is right. These are my two tries :

    The first one (which I prefer) is working with <link> (to include CSS files) but it's not working with <script> tags.

     $('head').append('<script type="text/javascript" src="'+addon+'"></script>');
    


    And the second one is by using get HTTP request. And here is my try :

     $.getScript(addon, function(){});
    


    So, the question is: what is wrong with the first code? Because I tried it before with <link> tags and its working so good.

  • mplungjan
    mplungjan about 11 years
    Good one. Didn't think of that
  • Sikshya Maharjan
    Sikshya Maharjan about 11 years
    @mplungjan: thanks! I like simplicity (when I'm thinking clearly, anyway...) =)
  • Admin
    Admin about 11 years
    Thats amazing, guys you're amazing, both solutions were right :D thanks too much!
  • Sikshya Maharjan
    Sikshya Maharjan about 11 years
    You're very welcome, of course; I'm glad to have been of help, and thank you for the accept. =)
  • techie_28
    techie_28 over 10 years
    @DavidThomas thats the prettiest way I saw to do this..Please refer me to a link where I can get more detail about such a use of jQuery object?..thanks.