javascriptangularjsangularangularjs-bindings

Download scripts inside Angular 2 innerHTML binding


I'm working on an Angular 2 application that is showing news items inside my application. The news items are saved in a database and loaded into the template using Angular's [innerHTML] binding.

A problem occurs when there is embedded content (like a Tweet) inside the news item's content, which requires a javascript file to be loaded (e.g. //platform.twitter.com/widgets.js). The problem is that the browser won't download the file, even after parsing the page.

Does anyone know how to solve this problem? Thanks!


Solution

  • I think if you have something like this it'll download the file. So when you get the news feed items, if you have any data on the news feed item when you can determine if it has twitter embedded into it you can check for it and then fetch what ever js file you need.

    loadedURLs = {
    // to hold a cache so you wont download more than once.
    };
    
    this.service.fetchDataFromDB()
    .subscribe(data =>{
       if(data.url.indexOf('twitter') != -1 && loadedURLs[data.url] == undefined){
         loadedURLs[fileURL] = fileURL;
         // send the file name you want or need.
         this.downloadJS(JSFileURL);
       }
    });
    downloadJS(fileURL){
       var script = document.createElement('script');
       script.src = (fileURL);
       document.head.appendChild(script);
    }