Using jQuery's append function will retrieve external source files within script tags, however, it will not officially render them in the DOM

After including a script with an external source and attempting to parse it using jQuery, the script is downloaded but not loaded into the DOM. This issue persists regardless of which jQuery DOM insertion method I use, such as .append().

Take a look at this example in Stack Snippets

$(function(){
  
  var selet2Html =
    '<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
    '<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
    '<select class="select2">' +
    '  <option value="AK">Alaska</option>' +
    '  <option value="HI">Hawaii</option>' +
    '</select>' +
    '<script >' +
    '  $(function() {' +
    '    $(".select2").select2();' +
    '  });' +
    '<\/script>';
    
  $("body").append(selet2Html);
  
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

Despite showing that the script has been downloaded in the network tab, an error occurs indicating that the external library (select2) was never loaded:

This problem still remains when using $.getScript(). Since I'm loading the string dynamically with .load(), I'm uncertain if it will contain any external scripts or not.

What steps should I take to successfully load the external library?

Answer №1

As dandavis mentioned, it is important to allow the library to fully load before initializing it. A simple approach would be to wait for a short period of time and then try again, like so:

setTimeout( function() {
  $(".select2").select2();
}, 2000);

Check out the Simple Demo in Stack Snippets:

$(function(){
  
  var select2Html =
    '<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
    '<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
    '<select class="select2">' +
    '  <option value="AK">Alaska</option>' +
    '  <option value="HI">Hawaii</option>' +
    '</select>' +
    '<script >' +
    '  setTimeout( function() {' +
    '    $(".select2").select2();' +
    '  }, 2000);' +
    '<\/script>';
   
  $("body").append(select2Html);
  
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

A more advanced solution involves waiting until $.fn.select2 is available in the DOM.

Introducing the OnAvailable Function

You can use this function as follows:

onAvailable('$.fn.select2', function() {
  alert('Success');
});

Below is the function that will continuously check for the variable within the global namespace to become available. It utilizes Alnitak's Object.byString solution from Accessing nested JavaScript objects with string key

function onAvailable(listenFor, callback) {
  var interval = window.setInterval(function() {
    if (Object.byString(window, listenFor)) {
      clearInterval(interval);
      callback()
    }
  }, 100);
};

Explore the Advanced Demo in Stack Snippets

function onAvailable(listenFor, callback) {
  var interval = window.setInterval(function() {
    if (objectFromString(window, listenFor)) {
      clearInterval(interval);
      callback()
    }
  }, 100);
};

function objectFromString(o, s) {
  s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
  s = s.replace(/^\./, '');           // strip a leading dot
  var a = s.split('.');
  for (var i = 0, n = a.length; i < n; ++i) {
    var k = a[i];
    if (k in o) {
      o = o[k];
    } else {
      return;
    }
  }
  return o;
}

$(function(){
  
  var select2Html =
    '<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>' +
    '<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js" ><\/script>' +
    '<select class="select2">' +
    '  <option value="AK">Alaska</option>' +
    '  <option value="HI">Hawaii</option>' +
    '</select>' +
    '<script >' +
    '  onAvailable("$.fn.select2", function() {' +
    '    $(".select2").select2();' +
    '  });' +
    '<\/script>';
   
  $("body").append(select2Html);
  
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>

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

Remove the initialization of the jQuery UI portlet

I am currently utilizing the jQuery UI Portlet and I am in need of the portlets being initialized as droppable. Currently, when the page loads, the portlets collapse by default. Appreciate your assistance. ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

Implementing custom validation in React to dynamically enable/disable buttons

I am working on a basic form that includes 3 input fields and one submit button. The submit button is initially disabled, and each input field has its own custom validation logic using regex. I am looking for a way to enable the button only when all the ...

The functionality of changing the category in the second carousel slider on click using JavaScript appears to

Creating a bootstrap carousel slider that dynamically changes based on the selected category. For example, clicking on the hammer category will display only hammer images, while selecting the compass category will show compass images. Everything worked sm ...

What methods are available for retrieving specific XML entries using JavaScript?

Hey there, I'm dealing with this XML code <book> <bookname>book1</bookname> <author>authorman</author> </book> <book> <bookname>book2</bookname> <author>authorperson</author> </book ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

How can I extract an array of objects from an array of arrays containing objects?

Here is the array I am currently working with: let findAllSegmentProjectMediaFilesXref = [ { it: 0, bt: 0, items: [ { mute: false, startPosition: 10, endPosition: 20, ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

Cookies in Node.js Express are not being incorporated

Currently, I am in the process of developing a nodejs application and facing an issue with defining cookies. Here is a snippet of the code that I am working with: var app = express(); app.set('port', process.env.PORT || 3000); app.set('vie ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

Capturing Screenshots with Ionic Framework

I am currently working on an Ionic application that utilizes geolocation via the Google API. However, I am facing a challenge with implementing a feature where a button in the upper right corner should take a screenshot and trigger a popover with options t ...

I am unable to select the first item when using select2.js and setting a placeholder

I am experiencing an issue with my <select> list that is styled using select2.js. Everything seems to be functioning properly, except for when a placeholder is used. Users are unable to select the first item in the list initially. If they choose any ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...