Load Bootstrap and Popper using Require.js and CDN

My goal is to utilize require.js to load bootstrap and jquery from a CDN.

Although similar questions have been asked previously (such as Steve Eynon's response in Issue Loading PopperJS and Bootstrap via RequireJS, Even After Using Recommended PopperJS Version), I have tried the suggested solutions without success.

Approaches I've Tried

The main HTML file includes...

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script data-main="js/market-place" src="js/lib/requirejs/require.min.js"></script>
</head>   
<body>
 html content etc.
</body>
</html>

The file js/market-place.js contains...

console.log( 'market-place.js');

requirejs(['./decision-market-common'], function(){
  console.log( 'common requirement met.');
  require(['bootstrap'], function( bootstrap){
    console.log( 'bootstrap requirement met.');
    });
  });

The file js/decision-market-common.js includes...

console.log( 'decision-market-common.js');

requirejs.config({
  paths: {
    jquery   : 'https://code.jquery.com/jquery-3.3.1.slim.min',
    popper   : 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min',
    bootstrap: 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min'
    },
  shim: {
    bootstrap: {
      deps: ['jquery', 'globalPopper']
      }
    }
  });


define( 'globalPopper', ['popper'], function( p){
  window.Popper = p;
  console.log( 'global Popper is set.');
  return p;
  });

Outcome

While using Chrome for development, I initially see the following results in the console...

market-place.js
decision-market-common.js
common requirement met.
global Popper is set.

However, I encounter a JavaScript error:

Failed to load resource: net::ERR_FILE_NOT_FOUND

Even though the CDN popper.js is successfully loaded, require.js attempts to load ./popper.js. Why is this happening?

Answer №1

The solution provided for the query related to Loading PopperJS and Bootstrap via RequireJS Issue not Effective didn't resolve the issue in my case.

Here's what I encountered:

  • I was using Bootstrap version 4.1.3 and couldn't switch to a different version.
  • I needed to customize Popper settings and couldn't use the bundled version.

Using the bundled version made it difficult to access the internal Popper instance within Bootstrap for customizations.

After some exploration, I discovered the "map" option in RequireJS (https://requirejs.org/docs/api.html#config-map) and added the following to my RequireJS configuration:

map: {
    '*': {
        'popper.js': 'popper'
    }
}

This adjustment allowed RequireJS to correctly identify Popper.

While this may not be the most ideal solution and results may vary, I hope sharing my experience proves helpful to others!

Answer №2

Discovering the solution...

Utilize Bootstrap version 4.0.0-beta for optimal functionality. Versions 4.0.0 through 4.1.3 have shown issues with requirejs support.

Alternatively, consider employing the bundle version of Bootstrap to access the latest updates without needing to link Popper. Since there is no CDN available for the bundle version, creating a local copy is necessary. Modify the file js/decision-market-common.js as shown below:

It is essential to explicitly console.log( 'decision-market-common.js');

requirejs.config({
  paths: {
    jquery   : 'https://code.jquery.com/jquery-3.3.1.slim.min',
    bootstrap: 'lib/bootstrap/bootstrap.bundle.min'
    },
  shim: {
    bootstrap: {
      deps: ['jquery']
      }
    }
  });

Furthermore, consider using requirejs() over require() for improved functionality.

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

Smooth-scrolling feature with touch interaction available in the scrollbar extension

Anyone here aware of a high-quality jQuery or CSS plugin for scrollbars that supports touch functionality and smooth easing? I've been on the lookout for one, but haven't had any luck so far. Even if it comes with a price tag, I'm interested ...

Creating a fade in or fade out effect in AJAX without using jQuery is a simple yet

Is there a simple way to achieve fade in or fade out effects in ajax without relying on jQuery? I'm looking for a solution that can add color or background color to make it visually appealing, especially for small web pages with poor internet connecti ...

Mastering Vue.js: Leveraging v-model within a v-for loop and implementing watchers

After retrieving a list of debits and credits from a server using the fetch function, I store them in my Vue application: const myApp = Vue.createApp({ data(){ return{ debits:[], credits:[], //cut } }, me ...

A guide on customizing bar colors in a jqPlot stacked bar graph

Is there a way to customize the colors for individual bars in a jqPlot stacked bar chart? I've searched through examples, but they all seem to use the default colors. How can I explicitly set different colors for each bar? Here is the current code sn ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

What is preventing me from accessing session data using nuxtServerInit?

When attempting to retrieve sessions, I encounter an issue. Is everything set up correctly in the following main files: server, config? store/index.js export const actions = { nuxtServerInit ({ commit }, { req }) { console.log(req); } The console log ...

The issue with HTML where the header and footer elements are continuously repeating when

I'm struggling with the title header and footer repeating on every printed page. I just want to show the title at the top of the page and display the footer at the end of the print page. Can anyone provide a solution or suggestion? You can view my fid ...

Looking for guidance on JavaScript - Implementing a different font family for each div element

I need help with customizing the font family for each individual post on my website. Currently, I am able to assign a cursive font to all posts within a class, but I would like each post to have its own unique font. Since I am doing this on load, I am fa ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

Exploring the art of div transitions and animations using React and Tailwind CSS

I successfully implemented the sidebar to appear upon clicking the hamburger icon with a transition. However, I am now facing the challenge of triggering the transition when the close button is clicked instead. I have attempted using conditional operations ...

Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using: setTimeout(function() {}, 100); Below is a snippet of my code: function change_country(id) { if (window.XMLHttpReques ...

Tips for utilizing a protractor ExpectedCondition by hand

Recently diving into Protractor, I'm aiming to set up an expect statement like so: expect(elementIsVisible).toBe(true); While exploring the EC (expected conditions) section in Protractor, specifically EC.visibilityOf, I find myself unsure about the ...

Redirect to a new URL using $routeProvider's resolve feature

Currently, I am in the process of developing an application that includes the following endpoint: .when('/service/:id?', { templateUrl: 'views/service.html', controller: 'ServiceCtrl', resolve: { service: fu ...

How can you modify Jquery show_hide so that the page automatically scrolls to the bottom of the concealed field when the button is clicked?

On my website, there is a button that reveals a map when clicked. The button is visible when the page loads, but once clicked, the map slides open and goes out of sight since the page loads at the top as usual. My goal is to have the page automatically scr ...

Verifying the visibility of a div and triggering its closure upon clicking outside of it

Would anyone be able to provide guidance on how I can merge these two scripts into one? Thank you in advance! $(document).ready(function(){ if ($('.myContainer').is(':visible')) { alert('Hello'); } }); $(doc ...

The GitHub-hosted package encounters a failure during the npm publish process

Last week everything was running smoothly, but now I am encountering an error and not sure what went wrong. (Apologies for the formatting as there are many lines of log) Running Node version: v10.15.3 Using npm version: 6.4.1 After executing npm publish ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

substitute a component with a different one if it is present

I'm currently working on a script that will automatically replace one element with another as soon as it is created, even when the page loads. Despite my attempts to use MutationObserver, I haven't been successful. var target = document.querySe ...

When registering the onHardwareBackButton event in Ionic, the back button continues to successfully navigate to the previous page

I recently started working with Ionic and encountered an issue with the onHardwareBackButton event. The event is functioning properly and directing me to the register function, but even after going to the register function, it still navigates back to the p ...

Automatically scrolling through a nested list in ReactJs

I have a chat list integrated into my web application. The entire webpage is scrollable, as shown in the image at the bottom. I would like the messages list to automatically scroll to the bottom whenever a new message arrives. To achieve this, I created a ...