The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<script type="text/javascript">
var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
});
</script>

However, when I include the identical JavaScript from the CDN in libraries.js as demonstrated below, it results in a

ReferenceError: Can't find variable: anime
.

<script src="{{ mix('/js/libraries.js') }}"></script>

<script type="text/javascript">
var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
});
</script>

Upon verification, mix is compiling correctly, and the JS is included in libraries.js.

The script remains unchanged, positioned in the same location; however, I am puzzled by why this issue persists. Might it be due to libraries.js loading after the script executes? If so, how can this be resolved?

This problem recurs frequently. My preference is to utilize mix() over asset(). While the aforementioned addresses one library, my goal is to consolidate most of the libraries into a single file like libraries.js. Presently, many are loaded through CDNs due to the previously explained dilemma.

Answer №1

Assuming that you have a file named resources/js/libraries.js, filled with require(); statements to import packages from npm, along with another JS file importing custom code, here's a suggestion:

You can consolidate these imports without needing a separate JS file by utilizing webpack like so:

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .extract([
        'bootstrap', 
        'popper.js',
        'lodash',
        'axios',
        'jquery',
        'vue',
    ]);

mix.version();

Then simply add this at the bottom of your layout:

<script src="{{ mix('js/manifest.js') }}"></script>
<script src="{{ mix('js/vendor.js') }}"></script>
<script src="{{ mix('js/app.js') }}"></script>
@stack('scripts')

vendor.js essentially replaces your libraries.js, while app.js contains your custom code.

By using mix.version(): If updates are made to your custom code and you run npm run prod, only app.js will be modified (a smaller JS file), leaving vendor.js (larger file) unaffected. This results in faster loading times as returning users will only need to load the minimal app.js, while the cached vendor.js remains unchanged.


To specifically address your issue, if the variable name anime is not being detected, ensure it is imported correctly in your JS file like this:

window.anime = require('animejs');

Answer №2

Execute the command npm run watch and give it another shot.

Answer №3

Perhaps this solution could be of assistance.

  1. I made sure to save the JavaScript file as .min.js.
  2. Instead of utilizing mix, I opted for asset to retrieve the JavaScript file.
<script src = "{{asset('js/anime.min.js')}}" type ="text/javascript"> </script>

Please verify this. No issues were detected during my examination.

The following is the full code that was tested:

<script src = "{{asset('js/anime.min.js')}}" type ="text/javascript">
</script>
  <script>
  var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
}).add({
    targets: '.ml6',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 1000
});
</script>

Answer №4

Consider encapsulating your inline javascript like so:

window.onload = function(){ // your code here };

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

What sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data: let data = [{ "x": "0", "y& ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

Tips for presenting JSON data retrieved using jQueryWould you like to know how

Is there a way to extract and display the user id from JSON values? I'm trying to access the user id value. $('User_id').observe('blur', function(e) { var txt = $('User_id').value; jQuery.ajax({ type: 'g ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

Modifying attributes of an object within a document using Mongoose

Encountering an issue where the sentiment object in my document is not updating. Within my Model Class, there's a field named sentiment of type Object structured like this: sentiment: { terrible: 0, bad: 0, okay: 0, good: 0, fantastic: 0 } ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

Emails sent through an HTML form submission should always include a valid "from"

I am currently in the process of creating a feedback form that allows individuals to provide anonymous feedback. I have explored nodemailer and node-sendmail, but I have encountered an issue with both requiring a from address. While I am aware that this ca ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Stop Ajax requests when there are blank spaces in Typeahead.js

I've been experimenting with typeahead.js and utilizing the BloodHound remote feature to load data. Everything is functioning properly, except that when I input only spaces in the textbox, typeahead still makes an ajax call. I'm wondering if th ...

Is it appropriate to use a component inside an entry component?

I'm currently working on a component that triggers a function to open a window: @Component({ selector: 'app-deposits', templateUrl: './deposits.component.html', styleUrls: ['./deposits.component.scss&apo ...

Dealing with Superagent and Fetch promises - Tips for managing them

Apologies for posing a question that may be simple for more seasoned JS programmers. I've been delving into superagent and fetch to make REST calls, as I successfully implemented odata but now need REST functionality. However, I'm facing confusio ...

It is essential for Jquery to properly evaluate the first JSON result, as skipping

I'm currently facing an issue where the first JSON result is being skipped when I try to evaluate a set of JSON results. Below is the Jquery code snippet in question: function check_product_cash_discount(total_id){ //check for cash discount ...

To open a popup menu with a text box, simply click on the text box

Whenever the text box text is clicked, a popup menu should open with a text box. Similarly, when the filter icon in the right side corner is clicked, a menu should open with a list of checkboxes. However, currently both menus are opening when clicking on b ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...