Mr Brimm
Mr Brimm

Reputation: 133

Including external js with requirejs

I have the following in my js file that is called by requirejs

    define([
      'jquery',
      'backbone',
      'mobiledetect'
    ],
 function($, Backbone, mobiledetect) {
  var MobileCheckView = Backbone.View.extend({
     initialize: function(){
     var md = new MobileDetect(window.navigator.userAgent);
     if (md.mobile() || md.phone() || md.tablet()) {
        $('#mho_app').popup('show');
     } 
     }
    });
     return MobileCheckView;
    }); 

I get Uncaught ReferenceError: MobileDetect is not defined when referencing the external file via path in my main.js file

I have tried defining it directly at the top of the file as well with no luck. What am I missing that's keeping the script from loading and giving me the object?

    define('mobiledetect', ['https://cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.3.6/mobile-detect.min.js'], function () {
       var md = new MobileDetect(window.navigator.userAgent);
       return md;
   });

Upvotes: 0

Views: 588

Answers (1)

Eric Bronnimann
Eric Bronnimann

Reputation: 951

I suggest using the paths configuration in RequireJS to set mobiledetect to the URL, like so. Note that the ".js" is left off of the URL. RequireJS will automatically add the ".js" extension.

require.config({
  paths: {
    'mobiledetect': 'https://cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.3.6/mobile-detect.min'
  }
});
require(['mobiledetect'], function (MobileDetect) {
  var md = new MobileDetect(window.navigator.userAgent);
  if (md.mobile() || md.phone() || md.tablet()) {
    alert('Mobile Device');
  }
  else {
    alert('Must be a desktop?');
  }
});

See this JSFiddle example to see the code in action. You will get an alert stating whether you are on a mobile or desktop browser.

Also, the parameter mobiledetect should be MobileDetect to match the new MobileDetect call.

Upvotes: 1

Related Questions