Klyner
Klyner

Reputation: 4163

How to load Scripts async with Angular

As I have some bad experiences with the mix of Angular and jQuery, I am trying to avoid jQuery in Angular. Right now, I should add some code to my Angular project but I am not sure how I should convert this. The code is coming from someone else who wants me to implement this in the project.

Within my project I have added all of the required libraries into the index.html. I think this is the only place where a library can be added.

Does someone know (if there is a way) how I can convert those jquery code lines into Angular or javascript code? Where in the project should I add this?

$('head').append( '<meta name="PAGENAME" content="$pagename">' );

$(document).ready(function() {

    $.getScript( "https://www.website.com/crsc/scripts/script.js" )
      .done(function( script, textStatus ) {
        console.log( 'loaded test' );
      })

      .fail(function( jqxhr, settings, exception ) {
               console.log('not loaded');     
      });

});

Upvotes: 0

Views: 5222

Answers (1)

gh9
gh9

Reputation: 10703

You can use app.run which will run like a main method before the app loads everything

     app.run(["scriptService"],function(scriptService){
        scriptService.GetScripts()
          .then(function(success){console.log("loaded test");},
         function(error){ console.log("not loaded");}
    }]);

Next all you have to do is make a script Service.

    app.factory("scriptService", ["$http", function ($http) {
                this.GetScripts = function ()
    { 
return $http.get(""https://www.website.com/crsc/scripts/script.js") .then(function(result) { return result});

    }

but in reality why do you not just import the script through a script tag? Loading a script async, since op didnt know that was an option I thought I would include it here ww3 schools async loading

  <script src="demo_async.js" async></script>

definition and Usage The async attribute is a boolean attribute.

When present, it specifies that the script will be executed asynchronously as soon as it is available.

Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page Browser Support The numbers in the table specify the first browser version that fully supports the attribute.

Upvotes: 3

Related Questions