Created
February 24, 2019 07:03
-
-
Save kumaraksi/e409fb571169895ae35afe1f143bd65b to your computer and use it in GitHub Desktop.
Lazy load google maps dynamic script injector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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