Only Load a script if it is needed

Only Load a script if it is needed.

I stumbled across this late 2021, and can't believe that:

a) I never found it before

b) It isn't more widely used and acknowledged. 

It could be that it is frequently used, but that I never recognised it's value, or that for some technical reason it is a "slower" way of doing it, but whatever, it works very well for me, and it keeps pages lighter, faster and Core Web Vitals is happy :-)

<script>
var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "https://maps.googleapis.com/maps/api/js?key=API-KEY&v=weekly&callback=initialize";

if ($('#map_canvas').length > 0 ) {
    document.body.appendChild(script);
    
    ...
10