在 JS 中动态加载 JS [英] Dynamically load JS inside JS
问题描述
我有一个动态网页,我需要在另一个 javascript 文件中导入一个外部 JS 文件(在 IF
条件下).
I have a dynamic web page where I need to import an external JS file (under an IF
condition) inside another javascript file.
我试图寻找可行的解决方案,但没有奏效.
I tried to search for a feasible solution but it didn't work.
我曾尝试使用 document.createElement()
将 JS 文件加载到 DOM,但它也没有奏效.显然 Js 已加载到 DOM 中,但在当前 JS 文件中无法访问.
I have tried loading a JS file to the DOM using document.createElement()
but it also didn't work. Apparently the Js was loaded into the DOM but was not accessible in the current JS file.
jQuery 中的解决方案也可以
Solution in jQuery will also be fine
推荐答案
jQuery 的 $.getScript()
有时会出错,所以我使用自己的实现,例如:
jQuery's $.getScript()
is buggy sometimes, so I use my own implementation of it like:
jQuery.loadScript = function (url, callback) {
jQuery.ajax({
url: url,
dataType: 'script',
success: callback,
async: true
});
}
并像这样使用它:
if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
//Stuff to do after someScript has loaded
});
这篇关于在 JS 中动态加载 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!