Load Javascript After document load in Leaflet Js

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

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">
    <meta charset="UTF-8">

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



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:


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?


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.