It must be GoogleMap when we talk about adding maps to our sites. GoogleMapAPI is quite easy to use, but we have to face the performance issue when using it as well.
Problem
<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx"></script>
<scrip>
const mapObject = new google.maps.Map(document.getElementById("map"));
</script>
We can detect the page speed by using Lighthouse
or access https://web.dev
directly.
If we include GoogleMapAPI like this, we could face the following problems.
Impact caused by third party code
When users access your web site, browser automatically downloads the third party libraries from each CDN. The bigger the library, the slower the page speed.
Images downloaded in the invisible area
Actually it’s not necessary to download the map images before user can see it.
Solution
Problem1: add async defer to script tag
This is recommended by Google’s article.
Adding async
, defer
to script tag as well as callback
makes the browser download GoogleMapAPI after all DOMS
being constructed.
<scrip>
// callback after GoogleMapAPI loaded
function initMap() {
const mapObject = new google.maps.Map(document.getElementById("map"));
}
</script>
<script defer async src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&callback=initMap"></script>
Problem2: LazyLoad google map
As the most common UseCase is using GoogleMap to display the address of company or etc, MapAPI isn’t need to be downloaded as soon as the page loaded.
We could implement this lazyload feature easily by Intersection Observer API.
<script>
// include <script src="xxxxx"></script> isn't necessary
function initMap() {
const mapObject = new google.maps.Map(document.getElementById("map"));
}
$(document).ready(function () {
const mapOb = new IntersectionObserver(
(entries, ob) => {
entries.forEach( entry =>{
// download GoogleMapAPI library when it's DOM is displayed
if(entry.isIntersecting){
$.getScript('https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&callback=initMap');
ob.disconnect();
}
});
},
{
rootMargin: '100px'
}
);
// monitor Google map's id=map dom
mapOb.observe(document.getElementById("map"));
});
</script>
Finish
Congratulations! We solved all the problems. And after re-running Lighthouse again, you’ll find that the Performance
score will be increased by at least 10 points.