根据页面中是否定义了元素,提供备用外部 Javascript 文件

Serve alternate external Javascript file depending on if elements are defined or not in the page

本文关键字:备用 外部 文件 Javascript 元素 定义 是否      更新时间:2023-09-26

好的,这是我的第一个问题。

设置:我们使用基于javascript的工具来A/B测试我们的着陆页设计。我需要版本 A(控件)链接到一个外部 javascript 文件,版本 B(变体)链接到备用 JavaScript 文件。

目标:在控件底部有一个内部 js 脚本,用于查看该工具实际上是否为 A 或 B 提供服务,如果为 true,则为哪个工具提供服务。结果指示应链接哪个外部脚本。

问题:无论该工具实际上是否为 A 或 B 提供服务,都会首先链接原始脚本,然后如果检测到该工具,则在此之后链接相应的脚本。

这是我的代码(对于任何新手错误,我提前道歉):

//script at bottom of original or tool-served control html page template
<script type="text/javascript">
valForTool = function () {
  var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
  if (variationId == 1) {
     var newScript = document.createElement('script');
     newScript.type = 'text/javascript';
     newScript.src = 'js/scripts.js';
     document.body.appendChild(newScript);
   };
}
originalValidation = function () {
  var newScript = document.createElement('script');
   newScript.type = 'text/javascript';
   newScript.src = 'js/scripts.js';
   document.body.appendChild(newScript);
}
$(function(){
  if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
     valForTool();
  }  else {   
     originalValidation();
  };   
});
</script>
//end script on control or original template  
//script on tool-served variation html template - will run after the above script
<script type="text/javascript"> 
$(function() {
     $('#project_info input[type=submit]').removeAttr('disabled');
     $('#project_info').unbind();
     var newScript = document.createElement('script');
     newScript.type = 'text/javascript';
     newScript.src = 'js/scripts2.js';
     document.body.appendChild(newScript);  
     $('.input_text').parent().addClass('contact_field');
 });
</script>
// end script on variation template

关于我做错了什么的任何想法?我是否提供了足够的信息?谢谢!我喜欢这个网站作为我问题的参考,但这是我第一次真正发布一个。

稍微

缩短一下,似乎你只是在这样做:

<script type="text/javascript">
$(function(){
   if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
      var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
      if (variationId == 1) {
          $.getScript('js/scripts.js', function() {runSecond();});
      }
   }else{   
          $.getScript('js/scripts.js', function() {runSecond();});
   }
   function runSecond() {
      $('#project_info input[type=submit]').removeAttr('disabled').unbind();
      $.getScript('js/scripts2.js');
      $('.input_text').parent().addClass('contact_field');
   }
});
</script>

现在看看这一点,很明显,无论这些 if/else 语句中满足什么条件,两个脚本都在运行,我真的不明白你想做什么,但我要做的第一件事是添加一些 console.logs 以查看这些 if/else 语句是否像它们应该的那样工作, 然后弄清楚应该在哪些条件下加载哪些脚本等?