Blog

How to Execute JavaScript, Including an External Script, Only When a DOM Element is Present
Posted on April 27, 2015 in JavaScript, jQuery by Matt Jennings

Below is an example using jQuery of how to load the Google Maps API V3 external script and instantiate a Google Map object only when the #map_canvas DOM element is present in the server-side HTML:

if($('#map_canvas').length) {
    document.write('<script type="text/javascript" src= "//maps.googleapis.com/maps/api/js?v=3.15&libraries=geometry,key=aizasybyqqf6tmy69h04110eqiz-ksj_oqyywyc&sensor=false">' + '<' + '/script>' +
    '<script type="text/javascript">google.maps.event.addDomListener(window,"load", TBMap.InitAfterPageLoaded);' + '<' + '/script>');
}

Leave a Reply