javascript - 根据条件动态地将脚本添加到我的应用程序
问题描述
我创建了一个与我的问题相关的plunker。
我有一个从登录页面开始的具有多个页面的应用程序。当我的应用程序首次加载时,它会加载index.html
运行我设置的脚本config.js
,然后将其重定向到login.html
. 这只是管理我想在整个应用程序中使用的一些设置。
在config.js
我已经设置window.localStorage.setItem("use_minified",true)
并且我想使用它login.html
来确定是否为我的应用程序使用缩小文件。
我看了几个问题,比如这个:
使用可能包含 document.write 的 src 动态添加脚本标签
我已经尝试过(正如您在我的 plunker 中看到的那样),但我收到了错误:
未捕获的错误:[$injector:modulerr] 无法实例化模块 myApp,原因是:错误:[$injector:nomod] 模块“myApp”不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。
解决方案
我的答案:
我保持index.html
不变,以便它调用config.js
并重定向到login.html
.
我将这些添加到我的config.js
文件中:
function init_scripts() {
var jsDirectory = "js";
var jsExtension = ".js";
if (JSON.parse(window.localStorage.config).use_minified) {
jsDirectory = "js_min";
jsExtension = ".min.js";
}
loadScripts([
"../lib/ionic/js/ionic.bundle.js",
"../cordova.js",
"https://cdnjs.cloudflare.com/ajax/libs/angularjs-toaster/1.1.0/toaster.min.js",
"/lib/ionic-datepicker-fork-ionic1/dist/ionic-datepicker.bundle.min.js",
"/" + jsDirectory + "/app" + jsExtension,
"/" + jsDirectory + "/page1" + jsExtension,
"/" + jsDirectory + "/page2" + jsExtension,
"/" + jsDirectory + "/page3" + jsExtension
], null);
}
function loadScripts(array, callback) {
var loader = function(src, handler) {
var script = document.createElement("script");
script.src = src;
script.onload = script.onreadystatechange = function() {
script.onreadystatechange = script.onload = null;
handler();
}
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild(script);
};
(function run() {
if (array.length != 0) {
loader(array.shift(), run);
} else {
callback && callback();
}
})();
}
在我的<head>
中,login.html
我删除了所有<script>
标签并替换了它们:
<head>
<script src="/js/config.js"></script>
<!-- Functions found in config.js -->
<script>
init_scripts();
init_stylesheets();
</script>
</head>
这似乎运行得很好。我也为样式表做了类似的事情,你可以看到我调用了init_stylesheets();
使用相同概念的函数。
推荐阅读
- c++ - 使用#define 声明函数
- asp.net-core-mvc - 文化不一致 - 剃刀视图和视图模型之间的模型绑定中忽略了小数点分隔符
- firebase - @firebase/数据库警告
- javascript - Javascript Google Cloud Function 尝试在 FirebaseDatabase 中获得新的附加值
- docker - 构建 docker 容器时超出最大深度消息
- validation - 如果返回 false,Cakephp 3 更新验证提供程序中的值
- ios - 如何在 App Store Connect 中批准新版本
- ruby - 在archlinux中构建docker容器时无法使用bundle安装nokogiri
- netflix-eureka - 无法向 eureka 服务器注册客户端(类路径中没有安全性)
- python - tkinter 显示来自 tcp 的数据