首页 > 解决方案 > 根据条件动态地将脚本添加到我的应用程序

问题描述

我创建了一个与我的问题相关的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”不可用!您要么拼错了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

标签: javascripthtmlangularjsionic-framework

解决方案


我的答案:

我保持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();使用相同概念的函数。


推荐阅读