Running/Loading angular applications with Jquery on existing pages

Ok, this article is not about using jquery inside angular2 application. This is an article about (if by some reason), you have a need to inject your angular application inside a fragment or a section of a page. Meaning it’s just a part of a more global application (don’t ask why).

Solution:

 
<script>	
  var serverUri = 'https://somerherewherethescriptsarehostedCDN/';
  //it will usually be just these but you never know
  myCss = [
    'styles.bundle.css?version=b53a7ad5029f0f049840',
  ];

  myScripts = [
    'inline.bundle.js?version=37d20dffb3000fed5e2a',
    'polyfills.bundle.js?version=8218f8a9f2a6334b1483',
    'vendor.bundle.js?version=9c8232590b2c23151493',
    'main.bundle.js?version=ee60bef08d06fb003fe6',
  ];

  myAppRootComponent = '<app-root></app-root>';

  $(document).ready(function () {

    $.each(myCss, function (key, item) {
      // add the compiled css (this is with ng build --prod).
      $('head').append('<link rel="stylesheet" href="' + serverUri + item + '" type="text/css" />');
    });
	
	//add the approot tag to point where the application should bind
    $("#page").append(myAppRootComponent);  
	
	//load scripts by specific order
    var d1 = loadScripts(myScripts,serverUri).done(function () {
      //do something else
    });
	
	function loadScripts(scripts, uri) {
      var deferred = jQuery.Deferred();

      function loadScript(i) {
        if (i < scripts.length) {
          jQuery.ajax({
            url: uri + scripts[i],
            dataType: "script",
            cache: true,
            success: function () {
              loadScript(i + 1);
            }
          });
        } else {
          deferred.resolve();
        }
      }
      loadScript(0);
      return deferred;
    }

  });
</script>

What you may be forgetting:

1.Don’t forget to include the base href in header and also jquery

<head>
    <base href="/">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

Leave a Reply

Your email address will not be published. Required fields are marked *