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. :)
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.
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.
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.
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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With