Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load modernizr in head but use it in require.js

I want to load modernizr synchronously in head to prevent a fouc. I am using require.js at before /body to load some other scripts in which I'd like to use modernizr for feature detection and such things.

What is the right way to do this or is it even recommended to do so? If I require modernizr in my scripts it gets loaded again, if I won't, it is undefined.

Thanks in advance. :)

like image 477
shapeshifta Avatar asked Apr 29 '13 13:04

shapeshifta


People also ask

Should js be in head or body?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Can I use require in script tag?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.

What is modernizr how modernizr works?

Modernizr is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them.

How do I install modernizr on my website?

Download the Modernizr library file and then add that file to the script tag of your HTML page. Example: In this example, We will check whether our browser supports HTML5 video or not using Modernizr.


1 Answers

If Modernizr is the 1st script loaded in head, then it is accessible from everywhere, so you can define simple wrapper like this:

define('modernizr', function () { return window.Modernizr });

This code may be put inside wrappers.js like this:

<head>
<script src="/js/vendor/modernizr.js"></script>   
<script src="/js/vendor/require.js"></script>  
<script src="/js/wrappers.js"></script>  
<script src="/js/main.js"></script>
</head>

Then in main.js

var scripts = document.getElementsByTagName('script')
  , src = scripts[scripts.length - 1].src
  , baseUrl = src.substring(src.indexOf(document.location.pathname), src.lastIndexOf('/'))

require.config({
  baseUrl: baseUrl
})
like image 158
Andrey Kuzmin Avatar answered Oct 13 '22 00:10

Andrey Kuzmin