简体   繁体   中英

angular4 Clear external script on component load

I'm trying to rewrite my jquery website on angular4. In my home component I'm loading an external .js file using this function:

public loadScript(url) {
        console.log('preparing to load...')
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(node);
}

It works well until I start to navigate between the pages. The issue is every time the script is loaded, its applying animations on different parts of my website, so when I navigate somewhere and return back the animations are applied twice and thats look weird.

Please for those who are experts in angular, don't suggest me to rewrite the code fully in angular.

My question is, how to refresh or flush all the previously loaded js effects on component load ?

Is it possible ? If yes, could you please suggest me on this.

My second questions is what cause all this behaviours? Is jquery layer totally separated from angular ?

PS. I have tried other approached of external script loading but all of them end up this way. This approach is very useful if I want to quickly convert my small existing projects in angular.

Update 1: Script is loaded in onAfterViewInit() and like this: this._dataService.loadScript('/assets/js/home.js');

I cant access the functions but animations and effects are applied to elements, which is enough for my goal.

Basically I found out a simple solution for this matter. Every time I load a component, I generate a random uuid number and apply it to my html tags. Then when the external script is loaded, it doesn't affect my current elements and everything is displayed correctly.

External JS:

function textLoader(uid) {

    var u = $("div."+uid+"[id^='block-']").hide(),
    h = 0;

    if (function d() {

        $("."+uid+" .text-block").hide();
...

Component TS:

constructor(private _dataService : DataService, private userService : UserService)
    {
        console.log('home constructor');

        this.uuid = "cc_" + this._dataService.getUUID();
    ...

ngAfterViewInit() {

        this._dataService.loadScript('/assets/js/home.js');     
        textLoader(this.uuid);

If you have your personal view on my approach or any other possible solutions, I would be glad to hear it. I'm have just an intermediate knowledge in angular2 and of course such kind of codes are not advisable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM