Last active
May 13, 2021 16:42
-
-
Save tyohan/5b67bfe3f1549ee884c90adc4be369eb to your computer and use it in GitHub Desktop.
How to load the Firebase Firestore with ES6 module without using the bundler tool. I use it to lazy load the Firebase Firebase in my vanilla web component. To use it you just need to import and construct an instance, then call load() and handle the promise resolve.
This file contains hidden or 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 default class FirestoreModule{ | |
constructor(apiKey,authDomain,databaseURL,projectId){ | |
this.promise=false; | |
this.db=null; | |
this.apiKey=apiKey; | |
this.authDomain=authDomain; | |
this.databaseURL=databaseURL; | |
this.projectId=projectId; | |
} | |
load() { | |
if (!this.promise) { | |
this.promise = new Promise(resolve => { | |
if (typeof window.firebase === 'undefined') { | |
this.addScripts().then(()=>{ | |
firebase.initializeApp({ | |
apiKey: this.apiKey, | |
authDomain: this.authDomain, | |
databaseURL: this.databaseURL, | |
projectId: this.projectId, | |
}); | |
// Initialize Cloud Firestore through Firebase | |
this.db = firebase.firestore(); | |
const settings = {/* your settings... */ timestampsInSnapshots: true}; | |
this.db.settings(settings); | |
resolve(this.db); | |
}); | |
} else { | |
resolve(this.db); | |
} | |
}); | |
} | |
return this.promise; | |
} | |
//Add script tags to document | |
addScripts(){ | |
return new Promise(resolve=>{ | |
const app = document.createElement('script'); | |
app.src = `https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js`; | |
app.onload = ()=>{ | |
const firestore = document.createElement('script'); | |
firestore.src = `https://www.gstatic.com/firebasejs/5.0.4/firebase-firestore.js`; | |
firestore.onload=()=>{ | |
resolve(); | |
}; | |
document.body.append(firestore); | |
}; | |
document.body.append(app); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment