Glad to see you in Magento blog! Hi everyone. We know that Javascript is compiled when the browser loads your webpage. However, sometimes you need to compile your script loaded by Ajax, how should you do? As default, the browser doesn’t compile the script responded by Ajax. If you use the function eval() to compile your script, the variable (defined in your Ajax response code) will be unavailable to call in your page. Thus I have a tip that may help you solve this issue. You can call the function below to compile your script loaded by Ajax.

// Compile your custom script
function compileJsAjax(yourScript){
var jsElement = document.createElement('script');
jsElement.type = 'text/javascript';
jsElement.text = yourScript;
var existedJs = document.getElementsByTagName('script')[0];
existedJs.parentNode.insertBefore(jsElement,existedJs);
}

For example:

new Ajax.Request(requestUrl,{
method: 'post',
postBody: '',
parameters: '',
onComplete: function(xhr){
var response = xhr.responseText;
var scripts = response.extractScripts();
for (var i=0;i<scripts.length;i++)
compileJsAjax(scripts[i]);
}
});

If your response is a Javascript source (such as: , you can modify the function to get and compile this source.

// Load and compile your script source
function ajaxLoadJs(jsSource){
var jsElement = document.createElement('script');
jsElement.type = 'text/javascript';
jsElement.async = true;
jsElement.src = jsSource;
var existedJs = document.getElementsByTagName('script')[0];
existedJs.parentNode.insertBefore(jsElement,existedJs);
}

I hope this helps. Thanks for reading! For other informative articles and updates, visit our Magento tutorial frequently!

Related Tutorials:

Author

Why Magestore? We believe in building a meaningful & long-term relationship with you.

Write A Comment