As per the documentation my page has to contain
<script src="https://code.responsivevoice.org/responsivevoice.js?key=YOUR_UNIQUE_KEY"></script>
I would like to avoid hardcoding my API key into index.html and to keep it in a separate file. I tried adding the responsivevoice script using js like:
const rvScript = document.createElement('script');
const api_key = "XXXXXXXX"
const src = 'https://code.responsivevoice.org/responsivevoice.js?key=' + api_key;
rvScript.setAttribute('src',src);
rvScript.onload = () => {
console.log(responsiveVoice.getVoices());
responsiveVoice.speak('Hello world')
}
document.body.appendChild(rvScript);
I get a list of voices in the console but "Hello world" is not played back.
Any ideas how to resolve this?
The trick is to create the tag loading the library on the fly and inject it into the DOM only when we need it. The idea here is that we create a function that we can call on the pages where we need the third-party library and dynamically create and inject the tag into the of the application.
const loadDynamicScript = (callback) => {
const existingScript = document.getElementById('scriptId');
if (!existingScript) {
const script = document.createElement('script');
script.src = 'url'; // URL for the third-party library being loaded.
script.id = 'libraryName'; // e.g. responsivevoice or googleMaps
document.body.appendChild(script);
script.onload = () => {
if (callback) callback();
};
}
if (existingScript && callback) callback();
};