最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Include a JS file using jQuery - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Mar 4, 2013 at 21:06 nalply 28.7k15 gold badges82 silver badges104 bronze badges asked Mar 4, 2013 at 20:46 ArWebDevArWebDev 431 gold badge1 silver badge3 bronze badges 3
  • 2 You MUST escape the end tag <\/script> – mplungjan Commented Mar 4, 2013 at 20:48
  • Do you realize they are both get requests? ;) – epascarello Commented Mar 4, 2013 at 20:55
  • $('head').append('<script type="text/javascript" src="'+addon+'"><\/script>'); Is it right way to append external js in our head section dynamically – Anup Commented Jul 3, 2014 at 11:23
Add a comment  | 

4 Answers 4

Reset to default 13

Have you considered:

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

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

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

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.

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
});
发布评论

评论列表(0)

  1. 暂无评论