Run the specified JavaScript code following an AJAX request

I am seeking a way to run a dynamically added script on a webpage (using innerHTML). While searching, I came across this link:

how to execute ajax output script

Although it is close to what I need, it hasn't quite solved my issue. When I make an AJAX request, I receive the following content along with other elements:

<link rel=StyleSheet href="/my/css/file.css" type="text/css"/>
<h1>Some header</h1>
<div>Some text</div>
<ul><li>Some text</li><li>Some Text</li></ul>
<script src='my/js/file.js'></script>

I am trying to evaluate this content after adding it to my container element (via innerHTML):

scripts = mycontainer.querySelectorAll('script');
for (k=0;k<scripts.length;k++){
    eval(scripts[k]);
}

However, I have not been successful. Do you have any suggestions? Please note that I do not want to use any libraries and I am only focusing on modern browsers without any fallbacks.

The CSS loads correctly, and the JS file exists and is properly referenced.

Answer №1

Assuming I don't have your code, here are some assumptions I'll make:

listscript.php

<?php
   //fetch script list somehow.
   $script_list = array('my/js/file1.js', 'my/js/file2.js', 'my/js/file3.js');
   echo json_encode($script_list);
?>

index.html

function fetchAjax(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
 if (window.ActiveXObject){
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])
   }
   catch(e){
    //ignore error
   }
  }
 }
 else if (window.XMLHttpRequest)
  return new XMLHttpRequest()
 else
  return false
}

var request=new fetchAjax()
request.onreadystatechange=function(){
 if (request.readyState==4){
  if (request.status==200 || window.location.href.indexOf("http")==-1){
   var scripts = eval("("+request.responseText+")")
   var headerID = document.getElementsByTagName("head")[0];
   for (k=0;k<scripts.length;k++){
      var newScript = document.createElement('script');
      newScript.type = 'text/javascript';
      newScript.src = scripts[k];
      headerID.appendChild(newScript);
   }

  }
  else{
   alert("Error occurred while making the request.")
  }
 }
}

request.open("GET", "listscript.php", true)
request.send(null)

References:

  • Retrieving JSON data from PHP using JavaScript

  • Guide on Dynamically Inserting Javascript

Answer №2

Unless a more efficient solution presents itself...

I will resort to making an AJAX call for each script src, and evaluating the result. I will share the pertinent code here shortly.

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

Techniques for implementing a JS script within a useEffect hook in a functional component

I am currently working on a useEffect hook in my project, within which there is an if-else block that includes a Javascript function called 'B1.X.Change' inside the else statement. However, I am facing difficulty binding 'B1.X.Change' t ...

Is it possible that the background color won't change on the second click?

Initially, my first click worked fine and successfully changed the background color. However, as soon as I added a second condition, it stopped working. var showBox = $('.show'); showBox.click(function(){ if (parseInt($(this).attr('v ...

Leveraging TypeScript enums in conjunction with React to anticipate a string prop

Trying to enforce strict typing for a Button component in React. How can I ensure a prop has a specific string value? The current effort yields Type '"primary"' is not assignable to type 'ButtonLevel' enum ButtonLevel { Primary = ...

Grails array using jQuery autocomplete with findByAll() function

Hello everyone, I appreciate the assistance in advance! I am currently attempting to utilize Grails findByAll() in order to retrieve a list for use in the jQuery autocomplete feature found at this link: https://jqueryui.com/autocomplete/ I believe I am cl ...

EJS Templates with Node.js: Embracing Dynamic Design

Is there a way to dynamically include templates in EJS without knowing the exact file name until runtime? The current EJS includes only allow for specifying the exact template name. Scenario: I have an article layout and the actual article content is stor ...

What could be causing the error message "Uncaught ReferenceError: userId is not defined" to appear for me?

Despite the fact that my alert($userId) is displaying 1 (which is the user id), I am still receiving an error indicating that userId is not defined. Any thoughts on why this might be happening? $('.postComment').on('click', function(ev ...

Maximizing code reusability in Javascript and React: A guide to avoiding repetition

While creating a back button feature for query processing, I found myself constantly using if statements to handle additional queries in the URL. Unfortunately, the '(([query, value]' format is necessary and requires an extra if statement each ti ...

Computed property not properly updating the v-if condition

RESOLVED: I have found a solution that almost solves the issue. By removing <div v-if="isFrameLoaded"> and binding the source data to <video>, the video now loads simultaneously with the request being sent. There is no data in getBLOB ...

Having trouble with my Node.js/Express/Mongoose application where I am unable to save posts using the .save method after the first post. Could this be related to a

Utilizing AJAX, Node.js, Express, Mongoose, and MongoDB, the data is successfully delivered via ajax to node.js and logs properly. However, only the first post is being saved in MongoDB. When sending posts after the first one, all the new data is logged, ...

Incorporate functionality into a button using jQuery

I am working on a table that displays data in different levels (Parent, Child, Grandson). When I click on the parent row, it expands to show new rows related to the child level. Similarly, clicking on a child row reveals a third level known as the grandson ...

Leveraging HTML5's local storage functionality to save and manage a collection of list elements within `<ul>`

I need help with saving a to-do list in HTML so that it persists even after refreshing the browser. Can anyone assist me? html <!DOCTYPE html> <html> <head> <title>My To-Do List</title> <link rel="sty ...

What is the reason why modifying a nested array within an object does not cause the child component to re-render?

Within my React app, there is a page that displays a list of item cards, each being a separate component. On each item card, there is a table generated from the nested array objects of the item. However, when I add an element to the nested array within an ...

Steering clear of Unique error E11000 through efficient handling with Promise.all

In my development work, I have been utilizing a mongoose plugin for the common task of performing a findOrCreate operation. However, I recently discovered that running multiple asynchronous findOrCreate operations can easily result in an E11000 duplicate k ...

Can we dynamically apply a class to the body depending on the domain in the window's URL?

Currently, I am developing a website for a company that has operations in both New Zealand and Australia. They have domains pointed to the same website with both .co.nz and .com.au extensions. I have written the following code to assign the class "austral ...

Building a fresh User profile with Firebase and Vue

Hey there! I'm currently in the process of developing a user system using Vue and Firebase. I've successfully included the necessary Firebase script in my project along with some code. However, I'm running into an issue where clicking on the ...

Managing global devDependencies with Node and npm: A comprehensive guide

As I develop a Node module, I have included devDependencies like jasmine-node and jshint that need to be globally installed. My goal is to access their binaries in my makefile / npm scripts without using require(). Despite my research, I'm still unsu ...

Navigating through nested nodes within an Angular directive can be achieved by

Here is some HTML code with a directive: <foo> <span>Bar</span> </foo> myapp.directive('foo', function () { return { restrict: 'E', replace: true, transclude: true, temp ...

Testing the material-ui toggle component by simulating a click event

Trying to test functionality based on the material-ui toggle component with jest and enzyme has been challenging for me. Even though my generic clickIt function usually works well with other material-ui components, it doesn't seem to trigger the stat ...

Utilizing Ajax to access a private static property at the page level through PageMethod

My webpage utilizes Ajax Page Methods to handle data processing. Upon the initial page load, users are prompted to select a year, which triggers a PostBack. The selected year is stored in a private static page-level integer property called SelectedYear. Wh ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...