Dynamically loading JavaScript through asynchronous requests (Ajax)

In a recent discussion on Stack Overflow, the topic of loading JavaScript code to an HTML file at runtime was raised. One method suggested involves simple loading an external JS file and executing it. However, there are two key issues with this approach: the timing of execution is uncertain and customization options are limited.

The following code snippet was shared:

var elemScript=document.createElement('script');
elemScript.setAttribute('type', 'text/javascript');
elemScript.setAttribute('language', 'javascript');
var txt = document.createTextNode(result);
elemScript.appendChild(txt);
document.head.appendChild(elemScript);

I have been using this code within an HTTP request where the variable result contains customized code generated by a PHP script. This allows me to dispatch functions that require this dynamic code.

Unfortunately, this solution does not work in Internet Explorer 8 or older versions. Should we continue exploring ways to make it compatible with these outdated browsers, or is it time to move on?

Any suggestions for alternative approaches?

Answer №1

If you're looking for a solution that is compatible with both Vanilla JS and jQuery, I recommend considering require.js. You can learn more about how it works here, especially in terms of loading scripts after the page has loaded.

For even more control over script loading in older and newer browsers, consider using the DomReady plugin provided by require.js. You can find more information on this feature here.

Answer №2

Update: Final Resolution:

In versions of Internet Explorer 8 and below, it is not possible to manipulate a script's code using innerHTML, innerText, appendChild(txtNode), or any other DOM manipulation techniques. The only viable method to execute a script enclosed within a string is by utilizing the eval function. This snippet has undergone testing in Chrome, Firefox, Safari, IE9, IE8, and IE7.

(function (window, undefined) {

    var loaded = false;

    function onScriptLoaded() // triggers after the external script loads
    {
        if (loaded)
            return;

       // this flag prevents redundant execution in IE versions supporting onload 
        loaded = true;

        // sample JavaScript retrieved from a PHP file
        var phpScriptText = "window.alert('This was added to external script using PHP');";

        // ensures cross-browser compatibility for this process
        window.eval.call(window, phpScriptText);
    }

    window.onload = function () { // loads external script and invokes onScriptLoaded upon completion
        var doc = window.document;

        var script = doc.createElement("script");
        script.type = "text/javascript";
        script.src = "externalScript.js";
        script.async = true;
        script.onload = onScriptLoaded; // effective in most browsers

        // handling for IE
        if (script.onreadystatechange !== undefined) {
            script.timer = setInterval(function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    onScriptLoaded();
                    clearInterval(script.timer);
                }
            }, 100);
        }

        doc.getElementsByTagName("head")[0].appendChild(script);
    };

})(window);

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

There is a lack of output coming from jasmine-node

Looking to expand my knowledge in JavaScript, Node.js, and jasmine, I recently started working on a test from "The Node Craftsman Book" called FilesizeWatcher. After setting up the package.json file and running "npm install" to add jasmine-node locally to ...

What is the significance of the NS_ERROR_UNKNOWN_PROTOCOL error code?

When attempting to make an AJAX request using Angular 1.5.9, my code is as follows: $http.get('localhost:8080/app/users').then(function(resp) { ... }); However, I am encountering an error that reads: "NS_ERROR_UNKNOWN_PROTOCOL" (...) stack: "c ...

Issue with numeric values not rendering properly using range slider in Ionic

In my Ionic project, I am attempting to create a range slider for selecting an age between 0 and 25 years old. The goal is to display the selected number when sliding, such as: "I'm 21 years old" Currently, my code is functional. However, it does no ...

What steps do I need to take in order to showcase my mongoose collection data on the user's screen?

I have been facing an issue with fetching data from my mongoose collection and displaying it on the client side. Instead of getting the actual data, I am receiving 'Object' on the client side even though the data is saved in the database. Can so ...

Oops! The specified vue-router route name cannot be found

My issue involves a vue component with a method that includes a router push attempting to navigate to another vue component: GetAnimal.vue: ... this.$router.push({ name: "/viewanimal", }); ... The routing mapping is set up like this: router.js: { ...

Display a popup box upon receiving the response from an AJAX request

I have successfully implemented an Ajax code that delivers the desired result. Now, I am looking to enhance this code so that when a response is received from Ajax, a popup/modal box will automatically open. Currently, I can manually trigger the opening o ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

Tips for integrating Grails ${createLink} into your javascript code

Below is a JavaScript function that I have: function GetSelectedItem() { var e = document.getElementById("country"); var strSel = e.options[e.selectedIndex].value; alert(strSel); var url = "${createLink(controller:'country', act ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

Having difficulty uploading an image using Ajax in Firefox

I am trying to use Ajax to upload an image to a PHP script, but I am encountering this Firefox Exception! An error has occurred making the request: [Exception... "'JavaScript component does not have a method named: "available"' when calling me ...

Submitting multiple parameters in a Jquery POST request

Being a beginner in HTML, jQuery, and AJAX, I have managed to post one object using the code below. However, now I am looking to post multiple objects when clicking the "submit" button (id=analsis) which will send the content of xyz object ids to 127.0.0.1 ...

During the jest test, I encountered a timeout error indicating that the test exceeded the 5000 ms limit

Here is the specific code snippet causing the issue: export const initializeSpotifySDK = async (token: string, trackId: string, contextUri: string, playbackStateChangeHandler: (state) => void, errorHandler: (message: string) => void): Promise< ...

What causes a function to be returned as null when it is appended or assigned as textContent?

There's something I've been trying to figure out and I'm curious to get an answer on why it behaves this way. const print_html = (param) => { let container = document.querySelector('Container'); console.log(test_function(pa ...

Having trouble with Webpack unable to locate the necessary import for Typescript type resolution? Need help resolving this issue?

My current project is utilizing typescript and has been constructed using webpack. Within my project, there exists a typings file originating from a third-party library, located at node_modules/@types/libname/custom.d.ts. This particular file contains a n ...

JavaScript group by first letter issueI am facing a problem when trying

Having an issue with my code that needs to group contacts by first letter: A. ADRIAN ANDREI ANGEL B. BENY BORRIS Z. ZEYN etc. The current code is not displaying the groups correctly. I want to list each contact under its initial letter. Below is ...

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Trying out the Send feature of Gmail API using Postman

Attempting to use the Gmail API for sending emails. Utilizing Postman as a tool to test requests and obtain correct code for web application integration, encountering an error: { "error": { "errors": [ { "domain": "global", ...

Execute the task from an external JavaScript file using npm

Utilizing node and npm as a task runner from gitbash cli has been successful for the most part. However, I am facing an issue where I am unable to call tasks in separate .js files from my package.json. Any assistance with the syntax would be greatly apprec ...

Implementing conditional visibility of divs in HTML using Bootstrap 4 dropdown-menu selection

I am working on a dropdown menu bar with 3 options. When the user changes the selected option, I need to show or hide specific div elements accordingly. Can anyone provide guidance on how to achieve this using jQuery? <link rel="stylesheet" href="htt ...