Include Modernizr in RequireJS and have the Modernizr in the head tags

einstein picture einstein · Nov 19, 2012 · Viewed 8.7k times · Source

I have a problem with RequireJS and Modernizr.

I want the Modernizr resource to be on the head. And everything else in the body. The reason is that Modernizr need to do some stuffs before DOMContentLoad. I want to be able to load the Modernizr module into other modules using RequireJS. How can I accomplish that both in dev and production environment? I use requirejs that pulls all dependencies and minifies all the resources. And the yeoman build replaces <script data-main="scripts/main" src="scripts/vendor/require.js"></script>with the minified version.

under the body tag:

<!-- build:js ikl.app.js -->
<script data-main="scripts/main" src="scripts/vendor/require.js"></script>
    <!-- endbuild -->
    <script>
    requirejs.config({

        paths: {

            'jquery'        : 'vendor/jquery',
            'handlebars'    : 'vendor/handlebars',
            'ember'         : 'vendor/ember',
            'ember-data'    : 'vendor/ember-data',
            'modernizr'     : 'vendor/modernizr' // This should be removed


        },

        baseUrl: 'scripts',


        shim: {


            'jquery' : {

                exports : 'jQuery'

            },

            'ember': {

                deps: ['jquery', 'handlebars'],
                exports: 'Ember'

            },

            'ember-data': {

                deps: ['ember'],
                exports: 'DS'

            },

            'handlebars': {

                exports: 'Handlebars'

            },

            'modernizr': {
                exports: 'Modernizr'
            }

        }

    });

    require([

        'modules/system/controllers/system.controller',
        'jquery',
        'ember',
        'ember-data',
        'handlebars',
        'modernizr'

    ], 
        function( systemController ) {
            systemController.renderView();
        }

    );

    </script>

Answer

George Mauer picture George Mauer · May 8, 2013

You should be able to get both.

  • First, remove your paths configuration that relates to modernizr, you won't need it
  • Next Load Modernizr in the head - this will create a window.Modernizr variable.
  • Finally, before your bootstrapping require, define the modernizr module

    define('modernizr', [], Modernizr);
    require(['foo', 'bar', 'modernizr'], function(foo, bar, modernizr) {
         //..profit
    }