Rich-text Reply

How to include script in head?

asmang 10-28-14

How to include script in head?

Hi,

 

I'm trying to load a script into the head of a page based on the example found at http://markgoodyear.com/2013/01/scrollup-jquery-plugin/.

 

I'm having a hard time placing the .js file, jQuery, and CSS into the head of my variation.  Does anyone have any experience with this that could lend a hand?

 

Thanks!

Greg

Level 2

JDahlinANF 10-30-14
 

Re: How to include script in head?

To add a CSS file into the <head> of a page, you can do like:

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "/path/to/cssfile/goeshere.css";
document.getElementsByTagName("head")[0].appendChild(ss);

 

Since Optimizely already comes with a pared down version of jQuery, you may not need to add it as part of your variation, but if you need to, you can do it like this:

var ss = document.createElement("script");
ss.type = "text/javascript";
ss.href = "/path/to/jQuery/goeshere.js";
document.getElementsByTagName("head")[0].appendChild(ss);

 


The fastest way to get CSS into a page, is to use jQuery to create a <style> block, like this:

$('head').append('<style>del.redline{color:green !important;}</style>');

 

I have never tried doing all 3 at the same time...  good luck!

martindell 11-07-14
 

Re: How to include script in head?

[ Edited ]

Hi Napoleon, thanks for the tips.  I tried adding a different stylesheet into the head of the page with your first block of code and it worked Smiley Happy  Only problem is that it applied the new CSS to all variants.

 

What I found is that I has to explicitly add similar code (with different CSS) to all variants.  Not sure why it worked but thought it might help someone else

 

 

JDahlinANF 11-10-14
 

Re: How to include script in head?

I'm curious how you added it such that it applied to all variations.

Perhaps you are using "Options --> Experiment Javascript"?

 

For my method above, for the variation I want to run some code, I use the "< edit code >" link at the bottom right corner and add the code there. I have yet to see this happen but I have seen other people mention this as well.

martindell 11-10-14
 

Re: How to include script in head?

Yeah, I just used the edit code box for the variant and it was functional in the original too - even though it didn't appear in the edit code box for the original.  I checked with Optimizely support and they said this behavour was expected when modifying stuff within the head of the page.  Adding separate code for the original 'kind of' sorted the problem - but you could clearly seethat the variant was loading the original stylesheet - and then the variant css.  Presumably the original was loading the same stylesheet twice.  A bit of a performance hit - but a functional test Smiley Happy