gpt4 book ai didi

javascript - 根据条件动态地将脚本添加到我的应用程序

转载 作者:行者123 更新时间:2023-11-30 19:50:05 32 4
gpt4 key购买 nike

我创建了一个 plunker与我的问题相关。

我有一个包含多个页面的应用程序,它从登录页面开始。当我的应用首次加载时,它会加载 index.html,它运行我设置的名为 config.js 的脚本,然后重定向到 login.html。这只是管理我想在整个应用程序中使用的一些设置。

config.js 中我设置了 window.localStorage.setItem("use_minified",true) 我想在 login.html 中使用它 以确定是否为我的应用程序使用缩小文件。

我看了几个问题,比如这个:

Dynamically add script tag with src that may include document.write

我已经尝试过(正如您将在我的 plunker 中看到的那样)但我收到了错误:

Uncaught Error: [$injector:modulerr] Failed to instantiate module myAppdue to: Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

最佳答案

我的回答:

我保留了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();它使用相同的概念。

关于javascript - 根据条件动态地将脚本添加到我的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572205/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com