javascript - 用纯 JS 在另一个 JS 文件中包含一个 JS 文件
问题描述
我想在纯 JS 的另一个 JS 文件中包含一个 JS 文件,所以没有 NPM 或 Yarn。
我不使用类/模块,那么我该怎么做呢?
我对纯 JS 的意思
Pure JS 是可以直接包含在 HTML 中的 JavaScript,如下所示:
<script src="path/to/pure-js-file.js"></script>
我试过的
这是我的两个文件:
app.js
require('./components/navbar.js');
components/navbar.js
alert('Navbar component!');
但我得到这个错误:
Uncaught ReferenceError: require is not defined
因为普通浏览器不知道 require 关键字。
解决方案
由于您不想使用模块,您可以使用 AJAX 调用加载附加脚本,然后使用 eval 运行它。这是最直接的方法,但由于 JavaScript 沙盒安全模型,它仅限于您的域。使用 eval 还为漏洞、黑客和安全问题打开了大门。你可以这样做:
function getFile(filePath) {
var httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
eval(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
};
httpRequest.open('GET', filePath);
httpRequest.send();
}
getFile('./components/navbar.js');
推荐阅读
- ios - 在已经为 iOS SceneKit 中的 SCNNodes 解除分配(对象设置为 nil)时过度释放
- mysql - SQL 在 SELECT 表中输入与实际表数据不同,基于 if 语句
- c# - Win32 API waveInGetErrorText 声明到 C#
- excel - 使用 ODBC 从 Tally 中提取数据到 Excel
- html - 如何从嵌套在 Div 中的无序列表中删除项目符号?
- kubernetes-dashboard - 如何登录 microk8s Kubernetes Dashboard?
- ruby-on-rails - Rails In Transaction,为什么锁定整个数据库而不是单个记录?
- php - 在使用 MySQLi PHP 的 FLOATS 查询之间查找 FLOATS?
- mysql - 试图获得在查询中获得最大利润的酒店的房间
- java - 解析多个 json 对象时出现问题,每个对象都有来自经过验证的 JSON 格式的多个数组-JavaString