【问题标题】:Load script in html based on cookie基于cookie在html中加载脚本
【发布时间】:2014-05-22 23:23:34
【问题描述】:

如何根据 cookie 值在 html 中加载脚本。我需要在开发和部署模式之间切换。

我正在使用 wro4j,但在 wro4j 分组的 js 文件中找不到错误。

<head>

if (getcookie(debug-mode) 加载以下脚本

<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/main-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-core.js"></script>
<script type="text/javascript" src="/assets/v/{{ASSET_VERSION}}/angular-app.js"></script>

否则加载此脚本

<script type="text/javascript">
    loadIndividualJsCssFiles('config/assets.xml');
</script>
</head>

如何做到这一点

【问题讨论】:

    标签: javascript angularjs cookies wro4j


    【解决方案1】:

    document.cookie 是浏览器中包含所有 cookie 信息的字符串。一个快速而肮脏的解决方案可能看起来像这样:

    function injectScript(src) {
        var script = document.createElement('script');
        script.src = src;
        script.type = 'text/javascript';
        document.body.appendChild(script);
    }
    
    if ( document.cookie.indexOf('debug-mode') > -1 ) {
        injectScript("/assets/v/{{ASSET_VERSION}}/main-core.js");
        injectScript("/assets/v/{{ASSET_VERSION}}/angular-core.js");
        injectScript("/assets/v/{{ASSET_VERSION}}/angular-app.js");
    
    } else {
        var el = document.createElement('script');
        script.type = 'text/javascript';
        script.text = 'loadIndividualJsCssFiles(\'config/assets.xml\');';
        document.head.appendChild(el)
    }
    

    注意:我自己没有测试过这个

    基本上,您只是在document.cookie 字符串中查找您要查找的cookie 的名称。

    更强大的方法可能包括将 cookie 字符串转换为键值数组。

    【讨论】:

    • Y U make rlemon 说 :( 这不是很好。
    • 我同意这条评论。
    猜你喜欢
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    相关资源
    最近更新 更多