Rich-text Reply

Why is there less flickering with this jquery solution than the vanilla js variation?

moritz 11-22-16

Why is there less flickering with this jquery solution than the vanilla js variation?


we could recognize a improvement in flickering when we use jquery instead of plain js. Now i want to know why optimizely behaves like that. 

Below you find the variation code #1 is without jQuery and #2 with. Both variation got the "force"-statement. I thought that the plain version would be faster with the force statement. Does optimizely do a check/polling on the plain js version at the point where the script tries to access the head?



/* _optimizely_evaluate=force */
var bgImage = ""; 
document.newCss = '.landingpage--key-visual{ background-image:url(' + bgImage + ') !important; }';
var head = document.getElementsByTagName('head')[0];
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
if (styleElement.styleSheet) {   // IE
  styleElement.styleSheet.cssText = document.newCss;
} else {

code#2 with jQuery:

/* _optimizely_evaluate=force */
var bgImage = "";

var newCss = '.landingpage--key-visual{ background-image:url(' + bgImage + ') !important; }';
$("head").append('<style>'+ newCss+ '</style>');



Best regards,


Webdeveloper for conversionrate optimization
Level 3

JasonDahlin 11-22-16

Re: Why is there less flickering with this jquery solution than the vanilla js variation?

You should expect to see some additional flickering in the JS version over jQuery due to jQuery's crowd-sourced performance tuning.  That is, unless you are using the most efficient vanilla JS  ever written and have minified it for speed, anything you code will be slower than plain JS.


if you want to shave a few more milliseconds off your code, try this:


'<style>'+ newCss+ '</style>'


"<style>.landingpage--key-visual{ background-image:url('') !important; }</style>"

and lose the lines where you declate bgImage and newCSS.


Also, I've heard (but not run benchmark tests myself) that insertBefore runs faster than append or appendChild. 


I suspect this is because, for example, if you know your pages have a <body> tag, you are able to insert before that tag as soon as the browser recognizes the tag's existence.  Whereas, for "append" to work, the element you are inserting into must be in some form of "complete" in order to be appended to (you cannot add to something that is currently being evaluated, it needs to complete first so that the append doesn't happen, say, in the middle of a <p> tag or similar).  Depending on the size of the element you are inserting into, the delay could be enough to register visually (plus, the more you let the <body> load, the more your script will be competing for browser memory, CPU cycles, and network bandwidth).

--Jason Dahlin
Analytics and Testing Guru Smiley Happy

Experimentation Hero