Dynamically load JS inside JS(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JS内部动态加载JS


基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01