简体   繁体   English

如何在动态添加的 js 文件中引用代码?

[英]How do I reference code in dynamically added js files?

I try to add js files dynamically.我尝试动态添加js文件。
I found several guides for that and in Page inspector, they all seem like they work… However, I cannot reference any code in the newly added files.我在页面检查器中找到了几个指南,它们看起来都有效……但是,我无法在新添加的文件中引用任何代码。

在此处输入图片说明

My three code examples that look like they work fine... but don't.我的三个代码示例看起来工作正常……但不是。

//v1
var th = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', scriptName);
th.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);

//v2
var s = document.createElement('script');
s.setAttribute('src', scriptName);
document.head.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);

//v3
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);

do i have to append the scripts differently or is my reference call wrong / not possible?我必须以不同的方式附加脚本还是我的参考调用错误/不可能?

the Guides that exactly explain my requirement seem somehow not to work for me ?!准确解释我的要求的指南似乎对我不起作用?!
https://www.kirupa.com/html5/loading_script_files_dynamically.htm https://www.kirupa.com/html5/loading_script_files_dynamically.htm
Dynamically adding js to asp.net file 动态添加js到asp.net文件

Thanks in advance for any help在此先感谢您的帮助

The three methods to add a script element are essentially the same * .添加脚本元素的三种方法本质上是相同的*

As dynamically added script elements do not load the resources synchronously, you need to listen to the load event on the global object.由于动态添加的脚本元素不会同步加载资源,因此您需要监听全局对象上的load事件。 DOMContentLoaded is another idea, but it fires too soon as it does not wait for resources to have loaded. DOMContentLoaded是另一个想法,但它触发得太快,因为它不等待资源加载。

Here is a demo with loading jQuery asynchronously.这是一个异步加载 jQuery 的演示。 The output shows the type of the jQuery variable, which will be "function" once that resource is loaded:输出显示了jQuery变量的类型,一旦该资源被加载,它将是“函数”:

 let scriptName = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.js"; // v3 let myScript = document.createElement("script"); myScript.setAttribute("src", scriptName); document.head.appendChild(myScript); console.log("Synchronous, jQuery =", typeof jQuery); document.addEventListener("DOMContentLoaded", function () { console.log("After DOMContentLoaded event, jQuery =", typeof jQuery); }); window.addEventListener("load", function () { console.log("After load event, jQuery =", typeof jQuery); });


* The first version also defines the type attribute, but the HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type. * 第一个版本也定义了 type 属性,但 HTML5 规范敦促作者省略该属性,而不是提供冗余的 MIME 类型。

Consider this working example:考虑这个工作示例:

 // dyn.js window.zzz = 1;
 <!--index.html--> <html> <head> <script> function includeJs(url) { if (!url) throw "Invalid argument url"; var script = document.createElement("script"); script.src = url; document.head.appendChild(script); } includeJs("dyn.js"); function documentLoaded() { alert(window.zzz) } </script> </head> <body onload="javascript:documentLoaded()"> </body> </html>

An obvious difference between your code and this is that the sample above loads the script during the document loading and the usage of the script code happens after the document has finished loading.您的代码与此代码之间的一个明显区别是,上面的示例文档加载期间加载脚本,而脚本代码的使用发生文档加载完成之后

If you need to do a late-loading of a dynamic script depending on some run-time parameters, here are some options:如果您需要根据某些运行时参数延迟加载动态脚本,这里有一些选项:

If you have control over the dynamically-loading script, you could add a function in your loader script and call it at the last line of the dynamically-loading script:如果您可以控制动态加载脚本,则可以在加载程序脚本中添加一个函数并在动态加载脚本的最后一行调用它:

 // dyn.js window.zzz = 1; if(typeof(dynamicLoadingFinished) != "undefined") dynamicLoadingFinished();
 <!--index.html--> <html> <head> <script> function includeJs(url) { if (!url) throw "Invalid argument url"; var script = document.createElement("script"); script.src = url; document.head.appendChild(script); } function documentLoaded() { includeJs("dyn.js"); window.dynamicLoadingFinished = function() { alert(window.zzz) } } </script> </head> <body onload="javascript:documentLoaded()"> </body> </html>

Another possible approach would be to use the good old XMLHttpRequest .另一种可能的方法是使用旧的XMLHttpRequest It will allow you yo either force synchronous loading (which is not advisable because it will block all JavaScript and interactivity during loading, but in certain situations can be of use):它将允许您强制同步加载(这是不可取的,因为它会在加载期间阻止所有 JavaScript 和交互,但在某些情况下可以使用):

 // dyn.js window.zzz = 1;
 <!--index.html--> <html> <head> <script> function includeJs(url) { if (!url) throw "Invalid argument url"; var request = new XMLHttpRequest(); request.open("GET", url, false); request.send(); var script = document.createElement("script"); script.text = request.responseText; document.head.appendChild(script); } function documentLoaded() { includeJs("dyn.js"); alert(window.zzz) } </script> </head> <body onload="javascript:documentLoaded()"> </body> </html>

or load the script asynchronously and wait for the request to finish:或者异步加载脚本并等待请求完成:

 // dyn.js window.zzz = 1;
 <!--index.html--> <html> <head> <script> function includeJs(url, finished) { if (!url) throw "Invalid argument url"; var request = new XMLHttpRequest(); request.open("GET", url, true); request.onreadystatechange = function () { if (request.readyState == 4 || request.readyState == 0) { if (request.status == "200") { var script = document.createElement("script"); script.text = request.responseText; document.head.appendChild(script); return finished(); } else throw request.responseText; } }; request.send(); } function documentLoaded() { includeJs("dyn.js", () => alert(window.zzz)); } </script> </head> <body onload="javascript:documentLoaded()"> </body> </html>

I believe the AJAX samples could be written also with the more modern fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ).我相信 AJAX 示例也可以使用更现代的fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) 编写。

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

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