简体   繁体   English

根据用户输入动态加载外部Javascript文件

[英]Load External Javascript Files Dynamically Based on User Input

I have N different javascript files and I would like to load only one of them in my HTML code based on a user input. 我有N个不同的javascript文件,我想根据用户输入在我的HTML代码中仅加载其中一个。 Can someone point me towards how I can accomplish this? 有人可以指出我如何实现这一目标吗? Thanks! 谢谢!

You can always dynamically insert a <script> tag into your DOM depending on some input: 您始终可以根据某些输入将<script>标记动态地插入DOM中:

var myScript = document.createElement('script');
myScript.setAttribute('src', 'http://example.com/somescript_depending_on_user_input.js');
document.head.appendChild(myScript);

This will dynamically inject a <script src="http://example.com/somescript_depending_on_user_input.js"></script> element into your DOM and load the desired script. 这将动态地将<script src="http://example.com/somescript_depending_on_user_input.js"></script>元素注入DOM并加载所需的脚本。 Once the script is loaded from the remote url it will be evaluated by the browser. 从远程URL加载脚本后,浏览器将对其进行评估。

And if you wanted to wait for the external javascript to actually be loaded (which is a different point in time compared to injecting a <script> element into your DOM) you could subscribe to the onload event. 而且,如果您想等待外部javascript实际加载(与在DOM中注入<script>元素相比,这是一个不同的时间点),则可以订阅onload事件。 This could be quite handy if you want to call some functions that are only defined within the dynamically loaded script: 如果要调用仅在动态加载的脚本中定义的某些函数,这可能非常方便:

myScript.onload = function() {
    alert('Youpee, my dynamic script was successfully loaded, I can use it in this callback');
};

Also note that if you want this to work in IE as well you might need to subscribe to the onreadystatechange event as shown in this article . 还要注意,如果您希望它也能在IE中工作,则可能需要订阅onreadystatechange事件,如this article所示。 This will make your code to work across different browsers. 这将使您的代码可在不同的浏览器上运行。

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

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