Hello Team,
I implemented your google map widget in the cornerstone but it’s increasing the page load speed.
So I tried to use this code to show map after user interaction like click, touch or scroll etc. I made a component with map widget called “google-map-component”.
And also made a raw content widget with this code
#lazy-map-placeholder {
width: 100%;
height: 100%;
}
--------------
But it’s not displaying the map. Can you help me?
add_action(‘wp_ajax_lazy_load_map’, ‘lazy_load_map_callback’);
add_action(‘wp_ajax_nopriv_lazy_load_map’, ‘lazy_load_map_callback’);
function lazy_load_map_callback() {
echo do_shortcode(’[cs_gb name=“google-map-component”]’);
wp_die();
}
add_action(‘wp_footer’, function () {
?>
<script>
(function () {
let hasLoaded = false;
function loadScript(src, callback) {
const script = document.createElement('script');
script.src = src;
script.async = true;
script.onload = callback;
document.head.appendChild(script);
}
function loadMap() {
if (hasLoaded) return;
hasLoaded = true;
const placeholder = document.getElementById('lazy-map-placeholder');
// Load HTML via AJAX
fetch('<?php echo admin_url('admin-ajax.php?action=lazy_load_map'); ?>')
.then(response => response.text())
.then(html => {
placeholder.innerHTML = html;
// Inject cs-google-maps if not already loaded
if (typeof cs === 'undefined') {
const csScript = document.createElement('script');
csScript.src = '<?php echo cs_js_asset_get("assets/js/site/cs-google-maps")["url"]; ?>';
csScript.onload = () => loadGoogleMapsAPI();
document.head.appendChild(csScript);
} else {
loadGoogleMapsAPI();
}
function loadGoogleMapsAPI() {
// Define callback before loading API
window.csGoogleMapsLoad = function () {
if (window.cs && typeof cs.init === 'function') {
cs.init(document.getElementById('lazy-map-placeholder'));
console.log("✅ Map initialized.");
}
};
// Load Google Maps API with callback
if (!window.google || !window.google.maps) {
const gmapScript = document.createElement('script');
gmapScript.src = "https://maps.googleapis.com/maps/api/js?v=3&key=???&loading=async&callback=csGoogleMapsLoad";
document.head.appendChild(gmapScript);
} else {
window.csGoogleMapsLoad();
}
}
});
// Remove interaction listeners
window.removeEventListener('scroll', loadMap);
window.removeEventListener('click', loadMap);
window.removeEventListener('touchstart', loadMap);
}
// Trigger on first interaction
window.addEventListener('scroll', loadMap, { once: true });
window.addEventListener('click', loadMap, { once: true });
window.addEventListener('touchstart', loadMap, { once: true });
})();
</script>
<?php
});