Search code examples
jqueryoptimizely

Make Optimizely Variation Code Cleaner


Just seeing if anyone had any suggestions on making the following code cleaner that I have in my variation code section of Optimizely:

window.scrollBox();
$("#related-posts").css({"z-index":"1"});
$("#optslidebox").replaceWith("<div id=\"optslidebox\" style=\"z-index: 2; right: -999px;\">\n\t<a class=\"close\"></a>\n\t<p>Recommended</p>\n\t<h2>WHO ARE YOUR FAVORITE RAPPERS' FAVORITE RAPPERS RIGHT NOW?</h2>\n</div>");
$("#optslidebox > h2").wrapInner("<a href=\"http://greenlabel.com/sound/rappers-who-skate-skaters-who-rap/\"></a>");

This is what I want to append to the body (one can edit html in Optimizely, but it's very messy):

<div id="optslidebox">
    <a class="close"></a>
    <p>Recommended</p>
    <h2><a href="#">WHO ARE YOUR FAVORITE RAPPERS' FAVORITE RAPPERS RIGHT NOW?</a></h2>
</div>

I'm wondering how I could store the div into a variable, and if it makes sense, the items within the optslidebox div. I'd also be interested in seeing how I'd implement all the variables to have them show up in the body.

Thanks in advance!


Solution

  • Instead of replaceWith you can use html since it looks like you're replacing just the innerHtml. We like to clean it up with array concatenation, but still keeping the loop intact

    So with that pattern it'd look like

    /* _optimizely_evaluate=force */ /*global $*/
    window.variationHtml = [
      '<a class="close"></a>',
      '<p>Recommended</p>',
      '<h2><a href="#">WHO ARE YOUR FAVORITE RAPPERS\' FAVORITE RAPPERS RIGHT NOW?</a></h2>',
    ].join('');
    /* _optimizely_evaluate=safe */
    $("#optslidebox").html(variationHtml);
    

    If things get more intense though we built a multiline templating function to help with not needing to array concat everything.

    /* _optimizely_evaluate=force */ /*global $*/
    
    // timpl | https://github.com/clearhead/timpl
    !function(n){"use strict";function r(n){var r=i.exec(n.toString());if(!r)throw new TypeError("Multiline comment missing.");return r[1]}function t(n,r){return n.replace(c,function(n,t){for(var i=t.split("."),o=i.length,s=r,u=0;o>u;u++){if(s=s[i[u]],s===e)throw'tim: "'+i[u]+'" not found in '+n;if(u===o-1)return s}})}n.timpl=function(n,e){return t(n.call?r(n):n,e||{}).replace(/^\s+|\s+$/g,"")};var e,i=/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)[ \t]*\*\//,o="{{",s="}}",u="[a-z0-9_$][\\.a-z0-9_]*",c=new RegExp(o+"\\s*("+u+")\\s*"+s,"gi")}(window);
    
    window.variationHtml = timpl(function () { /*
      <a class="close"></a>
      <p>Recommended</p>
      <h2><a href="#">WHO ARE YOUR FAVORITE RAPPERS' FAVORITE RAPPERS RIGHT NOW?</a></h2>
    */});
    
    /* _optimizely_evaluate=safe */
    $("#optslidebox").replaceWith(window.variationHtml);