简体   繁体   English

使用jQuery包含一个JS文件

[英]Include a JS file using jQuery

I actually have a problem with including JS file using jQuery. 我实际上有一个使用jQuery包含JS文件的问题。 I found many sources but no one work with me. 我找到了很多来源,但没有人和我合作。 I'm pretty sure that the path of the js file is right. 我很确定js文件的路径是正确的。 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. 第一个(我更喜欢)正在使用<link> (包括CSS文件),但它不能与<script>标签一起使用。

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


And the second one is by using get HTTP request. 第二个是使用get HTTP请求。 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. 因为我之前尝试过使用<link>标签并且它的工作非常好。

Have you considered: 你有没有考虑过:

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

This avoids having to manually escape the </script> closing tag. 这避免了必须手动转义</script>结束标记。

你必须转义结束标记<\\/script>否则你过早地关闭脚本

try $.holdReady(true); $.getScript("sample.js", function() { $.holdReady(false); }); 尝试$.holdReady(true); $.getScript("sample.js", function() { $.holdReady(false); }); $.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. 这可确保在触发onready对象之前完全加载js,从而可以确保动态包含的js的任何对象/函数都可用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM