Skip to content

Instantly share code, notes, and snippets.

@kumaraksi
Created February 24, 2019 07:03
Show Gist options
  • Save kumaraksi/e409fb571169895ae35afe1f143bd65b to your computer and use it in GitHub Desktop.
Save kumaraksi/e409fb571169895ae35afe1f143bd65b to your computer and use it in GitHub Desktop.
Lazy load google maps dynamic script injector
import { loadScript } from './scriptLoader';
export class GoogleMapScriptLoader {
static instance;
url;
promise;
constructor(){
if(GoogleMapScriptLoader.instance){
return GoogleMapScriptLoader.instance
}
this.url = `https://maps.googleapis.com/maps/api/js?key=<google maps api key>`;
GoogleMapScriptLoader.instance = this;
}
static getInstance(){
return new GoogleMapScriptLoader();
}
async loadGoogleMapLib(){
if (typeof google !== 'undefined' && google.maps) {
return Promise.resolve(google.maps);
}
try {
if (!this.promise) {
this.promise = loadScript(this.url);
}
await this.promise;
return Promise.resolve(google.maps);
} catch (err) {
console.error(err);
return Promise.reject(err);
}
}
}
export const loadScript = async (url, type = 'text/javascript') => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.type = type;
script.src = url;
script.onload = resolve;
script.onerror = reject;
script.async = true;
document.body.appendChild(script);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment