Rich-text Reply

Replace a jasvascript function which is loaded in an external .js

miguelm 11-05-15

Replace a jasvascript function which is loaded in an external .js

Hi,

 

There is jasvascript function which is loaded in an external .js, (The function is in a .js where all the javascript code is).

<script src="https://mywebsite/functions.js"></script>

I want to replace one of the functions which are in the .js file. How can I do it?

 

Thank you,

 

 

 

Level 2

JDahlinANF 11-05-15
 

Re: Replace a jasvascript function which is loaded in an external .js

@miguelm - you can add code in your variation that waits for the function to be defined and then redefines it to what you want it to be for this variation.  At the bottom of the example below, replace the two instances of "functionNameHere" with the name of the function you want to update and include the updated function code

 

/* _optimizely_evaluate=force */
function waitForDelayedContent(selector, experiment, timeout, keepAlive) {
    var intervalTime = 25;
    var timeout = timeout || 3000;
    var keepAlive = keepAlive || false;
    var maxAttempts = timeout / intervalTime;
    var attempts = 0;
    var interval = setInterval(function() {
        var selectorVal = (function(){
            try {
                return eval(selector);
            } catch(e) {
                return undefined;
            }
        })();
        if (typeof selectorVal !== 'undefined') {
            if (!keepAlive) {
                clearInterval(interval);
            }
            experiment();
        } else  if (attempts > maxAttempts) {
            clearInterval(interval);
        }
        attempts ++;
    }, intervalTime);
}

waitForDelayedContent("functionNameGoesHere", function(){
  functionNameGoesHere = function() {
    console.log('new function code goes here');
  }
});
miguelm 11-13-15
 

Re: Replace a jasvascript function which is loaded in an external .js

Thank you @nap0leon I'm going to try it! Smiley Happy

Level 2