在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.
我尝试使用<$将JS文件加载到DOM c $ c> document.createElement()但它也没有用。显然,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屋!