0

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;
   });

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

require(['mobiledetect'], function (MobileDetect) looks like the piece I needed. I did add paths in require.config in the main js file so I think I had that part right. Gotta try this on Monday, but this looks like it does the trick. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.