Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using async and inline JavaScript

I've added 'async' to some of my scripts (see below) however my back to top link script now doesn't display or function. Any ideas as I don't know JavaScript massively well and I can't seem to find the answers? below is the code that sits at the bottom of body:

<div class="sprite topsite active" style="display: none;">
<a href="#nav">Back to top arrow</a>
</div>

<script async src="content/js/hideaddressbar.min.js"></script>
<script async src="content/js/respond.min.js"></script>
<script async type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script async src="content/js/picturefill.min.js"></script>

<!-- back to top link -->
<script>
    $(document).ready(function() {
        // Show or hide the sticky footer button
        $(window).scroll(function() {
            if ($(this).scrollTop() > 200) {
                $('.topsite').fadeIn(500);
            } else {
                $('.topsite').fadeOut(300);
            }
        });

        // Animate the scroll to top
        $('.topsite').click(function(event) {
            event.preventDefault();

            $('html, body').animate({scrollTop: 0}, 300);
        })
    });
</script>

Any help would be gratefully appreciated, thanks!

like image 439
Michael Avatar asked Mar 08 '23 19:03

Michael


1 Answers

Your inline script is dependant on jQuery. So if you load jQuery asynchronously (the page will continue to load while jQuery loads in the background) you will have to wait with your scripts until jQuery is loaded.

I'd suggest you load jQuery first and synchronously, so that it can be the basis of your other scripts.

The async-attribute is meant to boost loading speed by loading scripts in parallel, that are not necessary at document.ready.

like image 51
zoku Avatar answered Mar 17 '23 00:03

zoku