Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Bootstrap, jQuery and local JavaScript - breaks jQuery

Currently I minify and concatenate my JavaScript and CSS files for my local 'theme'. Then I load the Bootstrap, jQuery and my local JavaScript/css files in the head of my website.

Whilst this works, it does result in 8 separate resource loads, rather than just 2 (1 for JS, 1 for CSS) which is what I would like to accomplish. (At this time I am not looking to asynchronously load multiple libraries).

I'm using Grunt in my build system in order to invoke the Uglify action to minifiy my JavaScript.

Below is the relevant part of my Gruntfile.js

uglify: {
    build: {
        files: [{
            src: ['src/main/webapp/js/vendor/*.js', 'src/main/webapp/js/*.js', '!src/main/webapp/js/output.min.js'],
            dest: 'src/main/webapp/js/output.min.js'
        }]
    }
}

I thought that by specifying the already minified jQuery and Bootstrap libraries to the Uglify action I could get it to combine the libraries with my minified 'theme' JavaScript. However when doing so, I then receive the following errors in my browser:

Uncaught Error: Bootstrap's JavaScript requires jQuery
Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: $ is not defined

Obviously by concatenating and minifying these files I'm breaking something.

Does anyone have any suggestions? I've tried using the minified and unminified versions of the Bootstrap and jQuery libraries just to be sure.

Cheers, Andy

like image 698
Andy Esser Avatar asked Sep 09 '26 03:09

Andy Esser


2 Answers

The problem is that you include bootstrap's javascript files before jQuery.

Bootstrap is jQuery dependent. You need to include jQuery first and then anything that needs jQuery.

like image 77
Ivanka Todorova Avatar answered Sep 11 '26 16:09

Ivanka Todorova


Assuming that you're using the standard grunt-contrib-concat for the concatenation, you need to ensure that you specify the files in the correct order.

For example, in my work Grunt config file (I work with Foundation rather than Bootstrap, but they are both dependent on jQuery) I have the following settings for my vendor/external files. build/external.all.min.js is the pre-minified code built up from jQuery first, then foundation, and then all the other scripts.

files: {
  'build/external-all.min.js': [
  'build/external/jquery.min.js',
  'build/external/foundation.min.js',
  'build/external/*.js']
}
like image 29
Andy Avatar answered Sep 11 '26 16:09

Andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!