【问题标题】:Enable a script tag based on another script启用基于另一个脚本的脚本标签
【发布时间】:2020-10-18 08:56:28
【问题描述】:

我正在尝试用 Javascript 编写一个脚本,该脚本可以根据 cookie 的值启用或禁用其他脚本。我会弄清楚如何单独设置 cookie,所以我现在只是硬编码。

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
</head>
<body>
    <script src="./script.js"></script>
    <script class="GA" src="./scriptga.js"></script>
</body>
</html>

script.js(伪代码,我不知道该怎么做):

var mycookie = 1

// enable script
if (mycookie=1) {
    enable script with class="GA";
    console.log("script enabled");
}
// disable script
else if (mycookie=2) {
    disable script with class="GA";
    console.log("script disabled");
}
// disable script
else {
    disable script with class="GA";
    console.log("script disabled");
}

scriptga.js:

console.log("script loaded");

任何帮助都将不胜感激,因为我在这近 6 个月的时间里断断续续地没有任何喜悦。 我不介意添加 jquery 或其他一些来实现这一点。

【问题讨论】:

  • 这是一个XY problem,因为一旦加载了脚本,就没有神奇的禁用方法。反过来做。不要在 html 中设置脚本标签,而是根据您的 cookie 逻辑创建它们
  • 如果这些脚本是你写的,那你为什么不使用函数/变量来调用和执行一段代码。

标签: javascript html conditional-statements


【解决方案1】:

假设您可以修改这些脚本(未从外部源加载) 无论如何都会加载两者,但您可以执行或不执行代码。

请记住,JS 将逐行执行并从左到右执行,因此请注意未定义的变量。

#1 使用变量

您可以将全局变量从script.js 传递到scriptga.js

  1. enableGA 定义为布尔变量。

script.js:

var mycookie = 1
// assume that you don't want to execute 'scriptga.js' by default
var enableGA = false; 

// enable script
if (mycookie == 1) {
    enableGA = true;
    console.log("script will be executed");
}
  1. 检查enableGA 是否为真。

scriptga.js:

if(enableGA){
   console.log("script executed");
}

#2 使用函数

script.js:

var mycookie = 1
// assume that you don't want to execute 'scriptga.js' by default
var enableGA = false; 

// enable script
if (mycookie == 1) {
    console.log("script will be executed");
    enableGA(); // call function
}

scriptga.js:

function enableGA(){
   console.log("script executed");
}

【讨论】:

  • 很棒的坦克 Mamdouh Saeed。我会试一试的,
【解决方案2】:

可以通过将脚本类型设置为type="text/plain" 来禁用脚本。现在将其设置回text/javascript 将不会运行它。您需要克隆脚本元素并再次插入。

然后:

<script type="text/plain" data-consent="ad_storage" src="js/analytics.js"></script>

<script type="text/javascript">
function enableScripts() {
    $("script[data-consent='ad_storage'][type='text/plain']").each(function(){
        $clone = $(this).clone();
        $clone.attr("type", "text/javascript").insertAfter(this);
        $(this).remove();
    });
}
</script>

【讨论】:

    猜你喜欢
    • 2017-10-23
    • 2022-08-22
    • 1970-01-01
    • 2014-11-18
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多