JS内部动态加载JS

2022-01-30 00:00:00 jquery javascript

我有一个动态网页,我需要在另一个 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
});

相关文章