I am loading/appending a 3rd party CDN script (using JQuery) on Component load. The Script is successfully appended into the DOM. But, unfortunately, if I go to other routes and come back to this component, the script is not executing anymore. Anyone has any clue how to solve this or what's possibly going wrong? Or how can I remove this Script everytime when I come to this route and load the Script again?
This is a Snippet of how I am appending the Script to DOM
loadScript(name: string) {
return new Promise((resolve, reject) => {
if (!this.scripts[name].loaded) {
//load script
let script = document.createElement("script");
script.type = "text/javascript";
script.id = this.scripts[name];
script.src = this.scripts[name].src;
script.charset = "UTF-8";
if (script.readyState) {
//IE
script.onreadystatechange = () => {
if (
script.readyState === "loaded" ||
script.readyState === "complete"
) {
script.onreadystatechange = null;
this.scripts[name].loaded = true;
resolve({ script: name, loaded: true, status: "Loaded" });
}
};
} else {
//Others
script.onload = () => {
this.scripts[name].loaded = true;
resolve({ script: name, loaded: true, status: "Loaded" });
};
}
script.onerror = (error: any) =>
resolve({ script: name, loaded: false, status: "Loaded" });
document.getElementsByTagName("head")[0].appendChild(script);
} else {
resolve({ script: name, loaded: true, status: "Already Loaded" });
}
});
} }
It's a bit hard to figure out the major reason to encounter this issue, but some ideas would be helpful to fix the problem.
Remove script
You can remove the script on ngOnDestroy()
event of the component.
Setting async
to false
As I know, by default, async
attribute for script
tags is true. So, to load script it would make problems. You could set this attribute like this:
//load script
let script = document.createElement("script");
script.type = "text/javascript";
script.id = this.scripts[name];
script.src = this.scripts[name].src;
script.charset = "UTF-8";
script.async = false; // set async
Caching in Angular
Last but not least, caching in SPA would make problem. As far as I'm concerned jQuery
sets caching JS to true. Make sure it makes no problem in your code.
I guess your issue is related to these items. You could check them step by step. I hope I could help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.