I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page.

index.vue

head: {
    bodyAttrs: {
      id: 'overview'
    },
    script: [
      {
        src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'
      }
    ]
  }

In the lower part of the page, version 1.8.3 is included in the CDN due to a jQuery plugin.

**/index.vue

head: {
    bodyAttrs: {
      id: 'lower'
    },
    script: [
      {
        src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js'
      }
    ]
  }

We have multiple JS files created with jQuery in the assets directory, which are modularized and imported. There are also other JS files present.

e.g.) ~/assets/useragent.js

/* global $ */
export default function () {
  // User agent
  var _ua = (function (u) {
    return {
      Tablet: (u.indexOf("windows") != -1 && u.indexOf("touch") != -1 && u.indexOf("tablet pc") == -1) || u.indexOf("ipad") != -1 || (u.indexOf("android") != -1 && u.indexOf("mobile") == -1) || (u.indexOf("firefox") != -1 && u.indexOf("tablet") != -1) || u.indexOf("kindle") != -1 || u.indexOf("silk") != -1 || u.indexOf("playbook") != -1,
      Mobile: (u.indexOf("windows") != -1 && u.indexOf("phone") != -1) || u.indexOf("iphone") != -1 || u.indexOf("ipod") != -1 || (u.indexOf("android") != -1 && u.indexOf("mobile") != -1) || (u.indexOf("firefox") != -1 && u.indexOf("mobile") != -1) || u.indexOf("blackberry") != -1
    }
  })(window.navigator.userAgent.toLowerCase());

  // Is in viewport
  $.fn.isInViewport = function (screen) {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = (viewportTop + $(window).height()) * screen;

    return elementBottom > viewportTop && elementTop < viewportBottom;
  };

  $(window).on('load resize scroll', function () {
    $('.shuffle-item--visible').each(function () {
      if ($(this).isInViewport(4)) {
        $(this).addClass('in_viewport');
      } else {
        $(this).removeClass('in_viewport');
      }
    });
  });
}

index.vue

mounted: function() {
    this.$nextTick(() => {
      if (process.browser) {
        JqueryEasing()
        MagnificPopup()
        useragent()
        }
    })
  }
}

Upon review, I found that the following should be added to nuxt.config.js.

nuxt.config.js

build: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.$': 'jquery',
        'window.jQuery': 'jquery'
      })
    ]
}

When running npm run dev, an error occurred during compilation:

These dependencies were not found:
* $ in ./assets/js/useragent.js
* jQuery in ./plugins/02_jquery.easing.1.3.min.js

To install them, you can run: npm install --save $ jQuery

How can I compile different jQuery versions using a CDN?

After further investigation, I decided to set it as external so that it is not read in the module

build: {
    extend(config, ctx) {
      config.externals = {
        jquery: 'jQuery'
      };
    }
}

Despite successful compilation, the page shows "Cannot find module 'jQuery' from '/ ~'" and remains inaccessible.

Answer №1

Have you found a temporary solution to the request for additional/correction to the question?

  1. Create a function that defines the process you want to execute immediately after loading jQuery using methods
  2. Associate the event with the function beforemounting
  3. Enable the firing of that event in the onload of the head script

Once jQuery is loaded in the head script, the methods are executed

head() {
    return {
      bodyAttrs: {
        id: 'photographer'
      },
      script: [
        {
          src:
            'https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js',
          async: true,
          onload: this.onJqueryLoad()
        }
      ]
    }
}

Specify the methods to be executed after loading

methods: {
    onJqueryLoad() {
      this.$nextTick(() => {
        if (process.browser) {
          JqueryEasing()
         MagnificPopup()
         useragent()
        }
      })
    }
}

The mounted method has been removed Everything else remains unchanged And it worked.

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

looping through the iteration

Here is a link to my original plunker demonstration: http://plnkr.co/edit/9UBZ9E4uxAo1TXXghm1T?p=preview. In the case of div 4 (ng-if="show==4"), I am looking for a way to hide the particular div when the list is empty. Currently, each div is displayed fo ...

Discovering an object by its id in vue-router parameters and subsequently sending its attributes to a template within Vue

In my ContactDetails component, I am fetching data from the vuex state and storing it in a contacts array. Then, within a computed property, I am attempting to find and return an object based on the id prop passed from the router params. Here is the code ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color. In Condition 1: When I click on the circle, both the text and circle colors are changed. In ...

Show a picture without specifying its file location

Looking for Suggestions on a New Title I am interested in using a script as the source attribute for an image, like this : <img src="img.js"/> Note: I am open to using any programming language, whether it be javascript or php. Here is what my fol ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...

The three.js library is throwing an error because it is unable to access the 'geometry' property of an

function CreateNewSphere(x, z) { var sphereGeometry = new THREE.SphereBufferGeometry(10 * factor, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({ color: SphereColor, wireframe: false }); var sphere = new THRE ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Managing selected ticket IDs in a table with AngularJS

I have a table that includes options for navigating to the next and previous pages using corresponding buttons. When I trigger actions for moving to the previous or next page (via controller methods), I store the IDs of checked tickets in an array $scope. ...

Execute a Bash script using Node.js based on a request from the client

I'm trying to find a way to execute a server-side script when a user clicks a button in the browser... After doing some research, I still can't seem to figure it out. Here's what we have: A Node.js server running on Fedora Red Hat (on lo ...

The code threw an error stating: "Error: Unable to set a new value to the unalterable property 'children' of the object '#<Object>'"

Encountering internal server error in Next.js build with Docker when reloading all routes with getServerSideProps react: "17.0.2" next: "^11.1.2" Local setup and deployment without Docker works fine, but with Docker implementation, reloading pages leads ...

Need a jQuery function that updates the 'id' after clicking on a specific div? Here's how to do it!

I need help simplifying my current situation. Step 1: I want to increment the variable "count" by 1 every time a specific div is clicked. Step 2: After updating "count", I want to utilize it in another function. This function involves copying the value f ...

"Transforming JSON data into structured key-value pairs using JavaScript

Develop a function named "json_filter" that accepts a JSON-formatted string as input. The accepted format is an array of objects, where each object contains keys for "mass," "density," "temperature," and "velocity," each mapped to a floating-point number. ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...

Effortlessly download multiple mp4 files simultaneously using jQuery through the console

When I open HTML pages in a new window, a media file ".mp4" is among the elements. To save only the media content within each page, I have this code: Is there a way to identify and download all external media files loaded on these pages? var anchor = docu ...

Selection of Dropdown results in PDF not loading

I am facing an issue with my function that selects a PDF from a dropdown list. Instead of loading and displaying the PDF, it only shows a blank modal. Any suggestions on how to fix this? <li> <a href="">Case Studies</a> <ul clas ...

Changing the website address | Node.js | Express

Is there a way to redirect incoming requests to different endpoints depending on a query parameter in the request? For instance, http://localhost:9000/?category=xyz&param1=...&param2=... The category value can be any of [abc, ijk, pqr, xyz]. Gi ...

Is it considered fashionable to utilize HTML5 data attributes in conjunction with JavaScript?

Currently, I am utilizing HTML5 data attributes to save information such as the targeted DOM element and to initialize events using jQuery's delegation method. An example of this would be: <a href="#" data-target="#target" data-action="/update"> ...

Is there an XML File Wrapper to Generate PDF Output?

Greetings Forum Members, I have been given the responsibility of creating a PDF file from multiple XML files. Has anyone come across an XML wrapper file before? This type of file would essentially contain a list of all the source XML file names in a spec ...

How the Marvel of jQuery Ignites the Power of

I require some assistance with the callbacks. It appears that they are not functioning properly. I am in the process of creating a jQuery-based game. I have designated a <div id='button'></div> for all the buttons that will be used ...