Nrc
Nrc

Reputation: 9787

Defer in jQuery cdn and conflict with jQuery UI

I use defer in the links to the cdn jQuery libraries:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js" defer>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" defer></script>

It seemed a good solution to the Google Page Speed requirements. If I do not use defer Google Page Speed says: Remove Render-Blocking Javascript

https://developers.google.com/speed/pagespeed/

But, as soon as I use defer, jQuery ui does not work. For instance, this piece of code needs ui. When I add defer, the animate does not happen. jQuery:

$("#button").click(function() {
    $(this).animate({ color:'blue' },1000);
});

Html:

<div id="button">SOMETHING</div>

Why defer cause problems with jQuery UI and how to solve that?

Upvotes: 2

Views: 1486

Answers (1)

Braunb&#228;r
Braunb&#228;r

Reputation: 31

You cannot rely on deferred scripts in your inline javascript code. You have to wait for the event DOMContentLoaded, which is fired after all deferred scripts are loaded:

document.addEventListener("DOMContentLoaded", function(event) {
    // now deferred scripts are loaded.
    $("#button").click(function() {
        $(this).animate({ color:'blue' },1000);
    });
});

Upvotes: 3

Related Questions