Search code examples
jqueryfancyboxpagespeedfancybox-3

The fastest loading of fancyBox/jQuery v3 without loosing scores in Google PageSpeed Insights


Currently we have fancyBox v2.1.5 and jQuery v1.11.3 in one of our old web projects. They are attached to the HTML pages right before the closing </body> tag like this:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
    if (typeof jQuery == 'undefined') {
        document.write(unescape("%3Cscript src='/scripts/jquery-1.11.3.min.js' type='text/javascript'%3E%3C/script%3E"));
    }
</script>

<script type="text/javascript" src="/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".fancybox").fancybox({
            beforeShow: function () {
                var alt = this.element.find('img').attr('alt');
                this.inner.find('img').attr('alt', alt);
                this.title = alt;
            }
        });
    });
</script>

</body>

The fancyBox's CSS is added like this in the <head> section:

<link rel="stylesheet" href="/fancybox/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />

When I launch Google's PageSpeed Insights test for our HTML pages, Google always mentions this CSS and tells us that we have 1 blocking CSS resource in above-the-fold content. To solve this problem and to make the load time of pages even better, I am going to upgrade to the latest versions of fancyBox and jQuery (which will also bring new features).

The home page of the fancyBox project tells us how to add the v3 to HTML pages:

<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js"></script>

If I add these lines before the closing </body> tag, will it help to achieve my goal? Are there any other tips how we can speed up loading of our pages when using fancyBox/jQuery (say, by adding the async attribute in the <script> tag or hosting fancyBox/jQuery files on our webserver)?

P.S. One possible problem with the suggested solution is that the <link> tag should be placed only in the <head> section, though it seems it works in body too in HTML5 (see this thread).


Solution

  • Check out Google recommendations - https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery and this SO thread - How to load CSS Asynchronously