I am currently using AJAX to load a fragment of a document. I have successfully loaded 'external' scripts, but I am encountering issues when trying to execute all the JavaScript within <script>
tags.
Below is an example of the HTML fragment I am attempting to load:
<textarea></textarea>
<script src="tinyMCE.js" class="ajax-script"></script>
<script class="ajax-script">
alert("I'm inline");
tinymce.init({
selector: 'textarea',
});
</script>
Here is the JavaScript code that I am using to load this document (on XHR status 200
):
// * This response is HTML
response = xhr.responseText;
// * Set the innerHTML of the body to the response HTML
document.body.innerHTML = response;
// * Find all scripts with ajax-script class
responseScripts = document.getElementsByClassName('ajax-script');
// * Loop through all those scripts
for (i = responseScripts.length; i--;) {
// * Create a 'clone' script element
cloneScript = document.createElement('script');
// * If the response script has a src, add it to the clone
if(responseScripts[0].src) {
cloneScript.src = responseScripts[0].src;
}
// * If the response script has 'inline code', add it
if(responseScripts[0].innerHTML) {
cloneScript.innerHTML = responseScripts[0].innerHTML;
}
// * Remove the original script
responseScripts[0].parentNode.removeChild(responseScripts[0]);
// * Append the clone script to the document
document.body.appendChild(cloneScript);
}
With this setup, only the alert("I'm inline");
portion of the inline code is being executed, while the rest is not. There are no console errors, and it appears that the browser is ignoring the tinymce.init()
part.
I am unsure if this issue is related to TinyMCE itself. Despite trying to evaluate the code, the problem persists. Interestingly, after the document loads, copying and pasting tinymce.init()
into the console results in the text editor displaying correctly due to the execution of the function.
Can you identify any reasons why only the alert
function is getting called, but not the rest? Do you notice any flaws in the script loading process?
Thank you.