JS内部动态加载JS [英] Dynamically load JS inside JS

查看:34
本文介绍了JS内部动态加载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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆