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.

1// Compile your custom script
2function compileJsAjax(yourScript){
3var jsElement = document.createElement('script');
4jsElement.type = 'text/javascript';
5jsElement.text = yourScript;
6var existedJs = document.getElementsByTagName('script')[0];
7existedJs.parentNode.insertBefore(jsElement,existedJs);
8}

For example:

01new Ajax.Request(requestUrl,{
02method: 'post',
03postBody: '',
04parameters: '',
05onComplete: function(xhr){
06var response = xhr.responseText;
07var scripts = response.extractScripts();
08for (var i=0;i<scripts.length;i++)
09compileJsAjax(scripts[i]);
10}
11});

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

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

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