简体   繁体   English

如何动态加载Javascript文件并立即使用它们?

[英]How to dynamically load Javascript files and use them right away?

I am using JQuery to inject dynamically script tags in the body tab of a webpage. 我正在使用JQuery在网页的正文选项卡中动态注入脚本标记。 I got something like : 我有类似的东西:

function addJS(url) {
  $("body").append('<script type="text/javascript" src='+url+'></script>'); 
}

I add several scripts this way, and try to use them right after. 我以这种方式添加了几个脚本,并尝试使用它们。 EG : EG:

lib.js lib.js

function core() {...}
alert("I'am here !");

init.js init.js

addJS("lib.js");
c = new core();

test.html 的test.html

<html>
  <head>
    <title>test</title>        
    <script type="text/javascript" src="init.js"></script> 
  </head>
  <body>
     Hello
  </body>
</html>

Loading test.html pops up "I'm here" and then ends up with an error "core is not defined". 加载test.html弹出“我在这里”然后最终出现错误“核心未定义”。 Of course merging both of the JS files will make them work perfectly. 当然合并两个JS文件将使它们完美地工作。

I just don't get it o_O. 我只是不明白o_O。

EDIT 编辑

I simplified this example, but Jeff answer made me understand that it was a mistake. 我简化了这个例子,但杰夫回答让我明白这是一个错误。 So here are some details : 所以这里有一些细节:

init.js is not in the head of test.html when it reload because I inject it with a code exectuted on a bookmarklet. 当重新加载时,init.js不在test.html的头部,因为我用一个书签上的代码注入了它。

So the real execution process is the following : 所以真正的执行过程如下:

reload test.html > run the bookmarklet > jquery and init.js are inserted > lib.js is inserted reload test.html>运行bookmarklet>插入jquery和init.js>插入lib.js

Sorry for the confusion. 对困惑感到抱歉。

EDIT 2 编辑2

Now I have the solution to my problem (that was quick :-)) but I am still interested to the answer to my question. 现在我有我的问题的解决方案(这很快:-))但我仍然对我的问题的答案感兴趣。 Why does this go wrong ? 为什么会出错?

jQuery使用getScript内置了这个功能。

You get the "core is not defined" error because the scripts are loaded asynchronous. 您得到“核心未定义”错误,因为脚本是异步加载的。 Which means that your browser will start loading lib.js in the background, and continue executing init.js, and then encounter "new core()" before the lib.js has finished loading. 这意味着您的浏览器将在后台开始加载lib.js,并继续执行init.js,然后在lib.js加载完成之前遇到“new core()”。

The getScript function has a callback that will be triggered after the script is finished loading: getScript函数有一个回调,将在脚本加载完成后触发:

$.getScript('lib.js', function() {
    var c = new core();
});

Notice your addJS function is appending to the end of the body element. 请注意,您的addJS函数将附加到body元素的末尾。

Since browsers will run scripts as they appear in the HTML source, 由于浏览器将运行HTML源代码中出现的脚本,

c = new core() 

will run before your lib.js script is loaded (at the end of the body element). 将在加载lib.js脚本之前运行(在body元素的末尾)。

I would recommend moving c = new core(); 我建议移动c = new core(); into the $(document).ready(function() {...}); 进入$(document).ready(function(){...}); or into a script element AFTER the body tag. 或者在body标签之后的一个脚本元素。

IMO, appending the script tag to the end of the document to load a script is rather unsightly. IMO,将脚本标记附加到文档的末尾以加载脚本是相当不雅观的。 Reason: 原因:

  1. you are trusting the browser to automatically fetch the script and load it. 您相信浏览器会自动获取脚本并加载它。
  2. You have no way of finding out whether the script is loading, has loaded, or if it encountered an error (maybe 404?) 您无法确定脚本是否正在加载,是否已加载,或者是否遇到错误(可能是404?)

The appropriate way would be to either use $.getScript(), or for a finer-grained control, fetch the script file with $.ajax() and use eval(). 适当的方法是使用$ .getScript(),或者使用更精细的控件,使用$ .ajax()获取脚本文件并使用eval()。

However, the second method has some issues: if you invoked eval() inside a function, then the script won't be available outside it! 但是,第二种方法存在一些问题:如果在函数内调用eval(),那么脚本将无法在其外部使用! This mandates workarounds... 这要求解决方法......

but why bother! 但为什么这么麻烦! use $.getScript() and get over with it :) 使用$ .getScript()并克服它:)

cheers, jrh. 干杯,jrh。

In response to why your code is failing: Adding a script tag to the body does not block further script execution. 响应您的代码失败的原因:向正文添加脚本标记不会阻止进一步的脚本执行。 Your code adds it, which starts the browser download process. 您的代码会添加它,从而启动浏览器下载过程。 Meanwhile, your script tries to call core() , which doesn't exist because lib.js hasn't finished downloading. 同时,你的脚本试图调用core() ,因为lib.js还没有完成下载,所以它不存在。 jQuery works because it waits till the script finishes downloading before executing your callback function. jQuery有效,因为它等待脚本在执行回调函数之前完成下载。

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

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