Krystian
Krystian

Reputation: 987

Speed optimization: Optimize render blocking scripts with async

On https://bm-translations.de (fully self coded, no cms etc.) I am trying to eliminate render blocking of <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>. Defer isnt working as I have another script at the end of the page <script src="globaljs.js"></script> that contains Bootstrap and jquery lazyloading etc as well as inline Javascript after it. I thought I could give async to all of them. At first I thought its working but from time to time (like random) its showing this:

I wondered if there is any other option or a way to ensure the render blocking jquery is loaded before the scripts at the bottom of the page but without render blocking?

Upvotes: 4

Views: 857

Answers (2)

Andrii Muzalevskyi
Andrii Muzalevskyi

Reputation: 3329

bm-translations.de doesn't need optimization of jquery loading, personal opinion. jQuery script doesn't block rendering, it is already placed at bottom

As far as I understood at the bottom of page there are 2 scripts. First is jquery, and second is dynamic, generated by server side for each page separately, which connects dynamic behavior to the HTML

BTW - Possible alternatives to placing JS before </body> end tag:

  • Build your scripts
    • just concatenate your scripts via script (for old projects this could work well)
    • use browserify, webpack, etc.
  • use RequireJS which could handle async scripts loading and loads dependencies
  • write custom JS which guarantees load order

But all these approaches seems to be not applicable to bm-translations.de

Upvotes: 1

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You could use the below approach to load the script sequentially with promises.

On DOMContentLoaded`` load the script sequentials and to load the scripts async you could use the ES6 promises.

Sample code:

document.addEventListener('DOMContentLoaded', async function(event) {
    await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js");
    await loadScript("globaljs.js");
});

function loadScript(src) {
    return new Promise((resolve, reject) => {
        let file = document.createElement('script');
        file.src = src;
        document.body.appendChild(file);
        file.onload = file.onreadystatechange = function() {
            resolve(true);
        };
    });
}

Upvotes: 1

Related Questions