AJAX does not execute all inline JavaScript code

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.

Answer №1

After facing compatibility issues with Chrome, I decided to implement jfriend's advice and converted the dynamic list into an array while ensuring synchronous script loading. Here is the revised approach:

response = xhr.responseText;
document.body.innerHTML = response;
responseScripts = document.getElementsByClassName('ajax-script');
i = 0;
// * Transforming DOM dynamic list into an array
function listToArray(list) {
  var array = [];
  for (var i = list.length >>> 0; i--;) { 
    array[i] = list[i];
  }
  return array;
}
function loadScripts() {
    if(responseScripts[i]) {
        cloneScript = document.createElement('script');
        if(responseScripts[i].src) {
            cloneScript.src = responseScripts[i].src;
        }
        if(responseScripts[i].innerHTML) {
            cloneScript.innerHTML = responseScripts[i].innerHTML;
        }
        responseScripts[i].parentNode.removeChild(responseScripts[i]);
        document.body.appendChild(cloneScript);
        if(cloneScript.src) {
            // * Waiting for external scripts to load
            cloneScript.onload = function () {
                loadScripts(i++);
            };
        } else {
            // * Calling the function again for inline scripts
            loadScripts(i++);
        }
    }
}
if(responseScripts.length > 0) {
    responseScripts = listToArray(responseScripts);
    // * Initiating script loading process
    loadScripts();
}

Answer №2

Below is an enhanced version of the concept presented in your response (taken from my feedback). Here are some key enhancements:

  1. Transformed it into a function for localized code
  2. Utilized var to declare all variables
  3. Made it more versatile by using passed-in arguments for reusability
  4. Avoided creating a stack with actual recursion
  5. Stored repeated references in local variables
  6. Applied Array.slice trick for array duplication
  7. Amended the script tag structure to allow either src= or .innerHTML but not both
  8. Centralized common code segments
  9. Switched from using .innerHTML to .textContent to solely extract text content

Modified Code:

function insertHtmlAndExecutescripts(elem, html, cls) {
    elem.innerHTML = html;
    var scripts = Array.prototype.slice.call(elem.getElementsByClassName(cls), 0);
    var i = 0;

    function loadScripts() {
        if (i < scripts.length) {
            var cloneScript = document.createElement('script');
            var tag = scripts[i++];
            if (tag.src) {
                cloneScript.src = tag.src;
                cloneScript.onload = function () {
                    loadScripts();
                }
                document.body.appendChild(cloneScript);
            } else if (tag.innerHTML) {
                cloneScript.textContent = tag.textContent;
                document.body.appendChild(cloneScript);
                setTimeout(function() {
                    loadScripts();
                }, 0);
            }

            tag.parentNode.removeChild(tag);
        }
    }
    loadScripts();
}

Answer №3

Experiment with logging the content returned by responseScripts[0].innerHTML. If this content contains the entire script, you can simply use the eval function to process it. However, if only the first line is present, then that may be the source of your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to change the height of a div element as the user scrolls using JavaScript exclusively?

Coding with JavaScript var changeHeight = () => { let flag = 0; while(flag != 1) { size += 1; return size; } if(size == window.innerHeight/2){ flag == 1; } } var size = 5; document.body.style.height = &qu ...

Executing a single Function within the UseEffect Hook

Can anyone assist me with solving this code puzzle? I have a carousel element that includes icons for moving to the previous and next slides. Whenever these icons are clicked, a specific function needs to be triggered within the useEffect() hook. The spec ...

Having trouble retrieving data through ajax with django

I'm having trouble showing sizes using AJAX, as they don't appear after the AJAX call is successful. Below is the AJAX script: <script type="text/javascript"> function getStoreView(event, productId) { event.preventDefault(); ...

Redirecting to an Unverified Website

I encountered an issue in my service.ts file where VeraCode code scan is failing Flaws by CWE ID: URL Redirection to Untrusted Site ('Open Redirect') (CWE ID 601)(16 flaws) Description The web application is vulnerable to URL redirection attacks ...

Toggle Canvas Visibility with Radio Button

As I immerse myself in learning Javascript and Canvas, the plethora of resources available has left me feeling a bit overwhelmed. Currently, I am working on a dress customization project using Canvas. // Here is a snippet of my HTML code <input type=" ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

AJAX failing to display correctly

I have been struggling to figure out why my AJAX code is not rendering as expected. Additionally, I am facing a less serious JS 'Parse error' that I can't seem to resolve. The issue arises with a preventDefault Rails form_for in which jQuer ...

Tips on arranging an array based on dates and data in JavaScript?

I have an array with dates and other data that I need to sort based on the dates. I'm unsure of how to go about this. Can someone please assist me? Here is the array in question: 0:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: ...

Having trouble getting the timer function to execute upon page load in JavaScript

My goal is to have my basic timer function activate when the page loads. However, I'm encountering issues with it not working as intended. I suspect there may be an error in the if else loop, possibly here: setTimeout(function(tag, sec), 1000);. How c ...

What could be the reason for the lack of functionality in this jQuery code when combining a for loop with the $

<!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ for(let i = 0 ...

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...

Using the Sequelize query string prefix to find data that starts with a specific value

I'm currently working on an autofill feature that takes a string input and provides a list of string suggestions. While using Sequelize's iLike:query, it retrieves all strings in which the queried string is present. However, my goal is to priori ...

JavaScript conflicts will arise due to the introduction of Yammer Embed on September 30th, 2014

Is anyone else encountering problems with Yammer embed causing JavaScript errors today? Our various applications across different technologies (SharePoint, IBM, etc) have been functioning normally for months, but this morning we are suddenly seeing a sig ...

Hiding a column in jQuery DataTables

Can the jquery datatables plugin be used to easily hide and show a table column? I've successfully refreshed the table data by using fnClearTable and fnAddData. However, I'm facing a challenge in one of my table views where I need to hide certa ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

Is it possible to integrate a backbone model with Angular?

Below is an example of a Backbone post model: var Post = Backbone.AssociatedModel.extend({ urlRoot: ApiService.resolveRESTUrl('posts'), defaults: { age : 0, fname : "", lname : "", manager : null }, ...

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

Resolving AJAX requests within a loop

I am working with a JSON file that contains widgets {"widgetname": "widget1", "widgetID": "FJRH585fKFJN234NC"} As I iterate through the JSON, I generate HTML for each widget object. $.ajax({ url: "get_json.php", data: {action: "get_widgets", ...

JavaScript Age confirmation Overlay

I designed an age verification popup with the help of some online tutorials and a friend due to my limited knowledge of JavaScript. Check it out live here- My issue is that I want this popup to load/appear after the page content loads, but I'm not s ...