How to compile Javascript loaded by Ajax?
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,existe dJs);
}
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: http://yourstore.com/test.js), 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,existe dJs);
}
I hope this helps. Thanks for reading! For other informative articles, visit our Magento blog!
Anyone wants $100 to purchase any extensions? JOIN NOW