Rich-text Reply

Appending external JS: errors in the editor then the script is not loaded on the live site

mkstvnsn 10-20-16

Appending external JS: errors in the editor then the script is not loaded on the live site

[ Edited ]

Below is the code that I'm using to load the external script. In the editor, I get an error when I add this that says ".replace on item 281 is not defined..", so I know that the editor is referencing the external file.

 

However, when I publish the update so I can test, the external JS file is not loaded on the page.

 

What am I doing wrong? How can I reference the external JS file so it actually gets loaded onto the page and I can reference functions from the script?

 

var loadScript = function(location, callback){
var fileRef = document.createElement('script');
fileRef.setAttribute('type','text/javascript');

if (callback) {
if (fileRef.readyState) { // IE
fileRef.onreadystatechange = function() {
if (fileRef.readyState == 'loaded' || fileRef.readyState == 'complete') {
fileRef.onreadystatechange = null;
callback();
}
};
} else { // Non-IE
fileRef.onload = function(){
callback();
};
}
}

fileRef.setAttribute('src', location);
document.head.appendChild(fileRef);
};

loadScript('http://www.website.com/files/script.js', function() {
});

Level 2

juliofarfan 10-28-16
 

Re: Appending external JS: errors in the editor then the script is not loaded on the live site

Whenever we debug a script which shows this kind of error, we usually go to our website at the page targeted and copy/paste the variation code into the console. If it doesnt work then your code ir wrong
JasonDahlin 10-31-16
 

Re: Appending external JS: errors in the editor then the script is not loaded on the live site

[ Edited ]

Hi @mkstvnsn,

If you move to Optimizely X, there are some built in utilities that let you "wait for object".  If you're on Optimizely Classic, you can do this:

 

/* _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("SomeVariableOrFunctionThatIsDefinedInYourExternalFileGoesHere", function(){
  /* The code you want to run once the thing is loaded goes here */
});

If you expect it will take longer than 3 seconds for you external file to load, like, maybe you want to make to 10 seconds, you can modify the waitForDelayedContent function call to be like this:

waitForDelayedContent("SomeVariableOrFunctionThatIsDefinedInYourExternalFileGoesHere", function(){
  /* The code you want to run once the thing is loaded goes here */
}, 10000);

or you can adjust this line:

var timeout = timeout || 10000;

 

 Also... the functions loaded by the window will be "window scoped" - so you may need to reference them like:

window.someFunction()

 

--Jason Dahlin
Analytics and Testing Guru Smiley Happy
robertchan 10-31-16
 

Re: Appending external JS: errors in the editor then the script is not loaded on the live site

You have a race condition. When your code is running at line 281, the external JS script has not yet fired. You need to fire the external JS script then do a callback on the rest of your script. Try putting all this into your variation code:

 

var appendJS = function(callback){

  var builtHeadScript = function(sourceLink) {

    var fileRef = document.createElement('script');
    fileRef.setAttribute('type','text/javascript');
    fileRef.setAttribute('src',sourceLink);
    document.head.appendChild(fileRef);

  };

  builtHeadScript('http://www.website.com/files/script.js');
  callback();

};

var takeAction = function() {
    appendJS(function(){
        // the code that follows after your script is attached
    });
};

takeAction();

Other factors I would consider if this doesn't work:

- Does your code after appending the JS use jQuery? If so, is there a race condition there?

- Do you need to scope out certain variables to window? For example, if you have something like var abc = 'cheezeburgers' which you can confirm functions as expected in your local environment or when you paste it into console as someone else on this thread mentioned, you might want to try scoping it out to window.abc = 'cheezeburgers'

Robert Chan