Load Javascript After document load in Leaflet Js

Hello!
I want to load specific JS code after document has been fully loaded in order to not affect the speed of the website so It is loaded after website speed measurment in google page speed

I have tested many ways ,non of them worked

Method 1 :

	window.addEventListener('DOMContentLoaded', function() {
        (function($) {
			 L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {}).addTo(mymap);
            //do something with b-lazy plugin, lightbox plugin and then with flexslider
        })(jQuery);
    });

Method 2 :

$(window).on('load', function() {
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {}).addTo(mymap);
});

Thanks in advance

Lighthouse identifies three types of blocking resources.

A <script> tag that:

  • Is in the <head> of the document.
  • Does not have a defer attribute.
  • Does not have an async attribute.

It sounds like you are after the defer attribute. This indicates to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

More info here:

Thanks @James_Hibbard I have added defer by making the script external but the script is not loaded

Strange. In principle, defer works like so:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>

    <script src="index.js"></script>
    <script>
        console.log("Hello");
    </script>
  </body>
</html>

index.js

console.log("Goodbye");

Given the above code, the browser will find index.js, download it, parse it and then log “Goodbye” to the terminal, before continuing on its way and executing the inline script block (and logging “Hello”).

If you add a defer attribute to the script tag:

<script src="index.js" defer></script>

The browser will defer downloading and parsing that script until it has finished with the rest of the document. Consequently the output will be:

Hello
Goodbye

It’s hard to say why this isn’t working for you without finding out some more details.

Do you see any errors logged to the console?

2 Likes

Thanks @James_Hibbard , but as I have said to you defer won’t work
I use this solution as temporay one (I am looking for one making load of script when user scroll down

$(window).on('load', function() {
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {}).addTo(mymap);
});

I’m afraid “won’t work” is too vague to offer much concrete help.
What exactly isn’t working about it?

Javascript provides an attribute “defer” used it <script src="your.js" defer> this way and yhis script will load when the whole website loaded completely.
If you want to load it separately in a background while website is loading use async in place of defer.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.