JavaScript does not recognize Bootstrap classes

I am utilizing Bootstrap 5.3.0 and have included it through CDN links in my JS script. This is how I am injecting it using my js file within the existing website's DOM via a chrome extension named Scripty, which serves as a JS injector extension for chrome:

function loadFile(path, type) {
    if (type == "js") {
      var fileref = document.createElement("script");
      fileref.setAttribute("type", "text/javascript");
      fileref.setAttribute("src", path);
    } else if (type == "css") {
      var fileref = document.createElement("link");
      fileref.setAttribute("rel", "stylesheet");
      fileref.setAttribute("type", "text/css");
      fileref.setAttribute("href", path);
    }
    document.getElementsByTagName("head")[0].appendChild(fileref);
  }

Then executing:

loadFile("https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13717c7c67606761726353263d203d23">[email protected]</a>/dist/css/bootstrap.min.css","css");
loadFile("https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77151818030403051607374259445947">[email protected]</a>/dist/js/bootstrap.bundle.min.js","js");

The loaded files are properly referenced in the header based on the browser dev tools inspection:

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbeb3b3a8afa8aebdac9ce9f2eff2ec">[email protected]</a>/dist/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10727f7f64636462716050253e233e20">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

However, when attempting to create an object later in my js script, I encounter an error stating that the bootstrap class is not recognized. Here is the code snippet used to initialize the new instance of the class:

const bsContactMenu = new bootstrap.Offcanvas('#contactMenu');

This is the error highlighted in the browser's dev tools:

Uncaught ReferenceError: bootstrap is not defined
    at AllInOne (<anonymous>:188:26)
    at <anonymous>:631:17

Although inspecting the exact class in the developer Tools->Watch confirms its definition, I am puzzled as to why I am receiving an error indicating it is undefined.

Observations from Developer Tools

It is expected that the bootstrap.Offcanvas class should be correctly interpreted by the browser since the developer tools verify its presence in the DOM.

Answer №1

One option is to wait until the DOM has fully loaded before executing the code:

document.addEventListener('DOMContentLoaded', function() {
  const bsContactMenu = new bootstrap.Offcanvas('#contactMenu');
});

Alternatively, you can also verify their inclusion order.

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

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

Guide on how to selectively add middleware such as multer to a fresh express router

For a previous project, I set up a router and utilized multer for handling file uploads. I was able to apply the multer middleware selectively on specific routes as shown below: var router = express.Router(); var multer = require('multer'); var ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

How can client-side routing be effectively utilized?

I have a question about the utilization of AngularJS and Node.js in my web application. I have implemented client-side routing using routeProvider to navigate within different pages. All data is retrieved from a RESTful API server-side. However, most of ...

Adjusting widths of strokes in React Native Vector Icons

I selected an icon from the react-native-vector-icon library. For instance, let's use featherIcons. How can I include a stroke-width property to the react-native-vector-icons package? import FeatherIcon from 'react-native-vector-icons/Feather&ap ...

Utilizing the datepicker options function within a different function

I'm working on a function that utilizes a promise to retrieve data from an asynchronous ajax call: $("#mySelect").on('change', function() { var mySelectValue = $('#mySelect').val(); var promise = getAvailableDates(mySe ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

What is the solution for addressing the absence of an 'Access-Control-Allow-Origin' header in the requested resource while using axios?

Here is my Vue script: <script> export default { ... methods : { login() { // uri -> http://my-app.test/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472b28202e2978222a262e2b7a332234330720 ...

The setAttribute method does not function with getElementByClass()

Can someone please help me understand why this code is not working for me: document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);'); I have confirmed that I do indeed have an eleme ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

Leverage the power of Angular's library dependency injection with the @inject

I am currently working on a project that involves a library. Within one of the classes in this library, I am attempting to provide a service using @optional, @host, and @inject decorators with an injection token. In the parent component, I have the optio ...

Executing AJAX calls within a forEach loop

I'm facing a challenge with a function that carries out a foreach loop on a list of views and needs to make an AJAX request for each view within the loop. Upon receiving the results in the success callback, it checks if a specific ID is returned and, ...

Encountering a Bad Request Response When Trying to Access WCF Service via Jquery Ajax

Encountered an issue when trying to call a WCF web service using jQuery Ajax, resulting in a bad request error without clear insight into the root cause. The service is not triggering any methods - neither success nor failure. Both the web service and the ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Toggling dropdown menus with conditional Jquery statements

I am experiencing some discomfort. :) I've been working on a calorie calculator that includes a dropdown for various dietary preferences. Currently, when a user clicks the button, the dropdown appears and disappears when clicking outside the button. ...

Error: This Service Worker is restricted to secure origins only due to a DOMException

Having trouble implementing this on my website; it keeps showing the following error. Help, please! Service Worker Error DOMException: Only secure origins are allowed. if ('serviceWorker' in navigator && 'PushManager' in wind ...

A glitch in showcasing the hello world example in Node.js with express

I've been diving into learning node.js and I'm eager to use the express framework. However, I hit a roadblock when trying to run a simple "hello world" example from the expressjs.com website. Instead of seeing the expected output, I encountered a ...

The data stored in LocalStorage disappears when the page is refreshed

I'm facing an issue with the getItem method in my localStorage within my React Form. I have added an onChange attribute: <div className = 'InputForm' onChange={save_data}> I have found the setItem function to save the data. Here is ...

Utilize JQuery to inject both standard HTML elements and safely rendered escaped HTML onto a webpage

After storing some data in firebase that can be retrieved on the client side, I use JQuery to add it to the HTML. Although the process of prepending the data to the DOM element is straightforward, there is a security concern as raw code can make the applic ...