CD2在angular2中的后备

时间:2016-10-11 21:05:12

标签: angular cdn

我想从CDN引用一些引用链接,但是如果cdn链接由于某种原因失败,它还希望有回退机制,它应该自动引用本地版本。 我在网上搜索但在Jquery中找到答案,任何想法如何处理angular2?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

1 个答案:

答案 0 :(得分:0)

我需要相同的东西,但只针对CSS部分,所以我想出了以下内容。

我添加了app.component.html

的第一行
<span class="bs hidden"></span>

AppComponent课程中,我添加了ngAfterViewInit函数和一个帮助_getElementStyle函数,如下所示:

import { Component, AfterViewInit, Renderer } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
}) 
export class AppComponent implements AfterViewInit {

  constructor(private _renderer: Renderer) { }

  ngAfterViewInit() {

    let bs = this._renderer.selectRootElement('.bs.hidden');
    if (this._getElementStyle(bs, 'display') !== 'none') {
      let link = [].slice.call(document.getElementsByTagName('link')).find((link: any) => {
        return link.rel && link.rel === 'stylesheet' &&
          link.href && link.href.indexOf('bootstrap') !== -1;
      });

      if (link) {
        link.href = 'assets/bootstrap.min.css';
        link.removeAttribute('integrity');
        link.removeAttribute('crossorigin');
      }
    }

    bs.remove();
  }

  private _getElementStyle(elem: any, declarationName: string): string {

    if (typeof elem === 'string') {
      declarationName = elem;
      elem = this;
    }

    // Element does not exist.
    if (!elem || typeof elem !== 'object') {
      return undefined;
    }

    let win: Window = window || document.defaultView;
    let style: CSSStyleDeclaration | any;

    style = win.getComputedStyle /* Modern browsers */
      ? win.getComputedStyle(elem)
      : elem.currentStyle /* IE 8- */
        ? elem.currentStyle
        : elem.style; /* Ancient browsers */

    declarationName = win.getComputedStyle
      ? declarationName.toLowerCase()
      : elem.currentStyle
        ? declarationName.replace(/\-(\w)/g, (str, letter) => {
          return letter.toUpperCase();
        })
        : declarationName;

    return style[declarationName];
  }
}

希望这有帮助。