Magento 2 – How to Use Loader Widget

javascriptmagento-2.1

I would like to show a loader using the Magento's default loader widget on my ajax call. When user clicks the submit button I would like to show the loader for 1 second and then hide it.

I am using something like this :

<script>
    require([
        'jquery',
        'jquery/ui',
        'mage/loader',

    ], function ($, loader) {
        $(function () { // to ensure that code evaluates on page load

           $.ajax({
             ... 
            })

Best Answer

It's impressively simple:

 $('body').trigger('processStart');

And to remove it

$('body').trigger('processStop');

Source code can be found here.

Result:

enter image description here


Note on loading scripts after page load

Quick tip, if a require JS file is required on page load add domReady! as a dependency rather than the jQuery function method. If you do it with a jQuery function other modules will not be aware of the page load dependency.