角度加载 css 文件需要时间并在控制台中抛出错误

Angular loading css files taking time and throw error in console

本文关键字:控制台 错误 出错 时间 加载 css 文件      更新时间:2023-09-26

我正在使用Angular-seed初学者项目,我想根据用户选择的语言加载CSS文件。每个 css 文件有 2 个文件。我有一个ltr-bootstrap.css来加载英语的所有内容,rtl-bootstrap.css加载 rtl 版本。

来解决这个问题。我在 HTML 中添加了一个控制器,以便我可以控制用户选择的语言并更改文件名。这是代码:

索引.html:

<!DOCTYPE html>
<html ng-app="myApp" dir="{{dir}}" ng-controller="HeadController">
<head>
  <meta charset="utf-8">
    <base href="/">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Angular seed</title>
    <!-- For browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="css/{{rtl}}bootstrap.css">
    <!-- custom style -->
    <link rel="stylesheet" href="css/{{rtl}}style.css">

</head>
<body>
    <ul class="menu">
        <li><a href="/view1">view1</a></li>
        <li><a href="/view2">view2</a></li>
    </ul>
    <div ng-view></div>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <!-- In production use:
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>
    -->
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-css/angular-css.min.js"></script>
    <script src="app.js"></script>
    <script src="view1/view1.js"></script>
    <script src="view2/view2.js"></script>
    <script src="dist/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

应用.js

'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.view1',
    'myApp.view2'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
    //$locationProvider.hashPrefix('!#');
    $routeProvider.otherwise({redirectTo: '/view1'});
    $locationProvider.html5Mode(true);
}]).
controller('HeadController', function($scope) {
    $scope.rtl = 'rtl-';
    $scope.dir = 'rtl';
});

一切正常,正在加载rtl-bootstrap但需要时间。因为一旦我登录到 localhot:8000 ,它就会尝试加载 css 文件,然后加载角度,因此它会在控制台中抛出错误:

GET http://localhost:8000/dist/bootstrap/css/%7B%7Brtl%7D%7Dbootstrap.css 
localhost/:23 Not Found
GET http://localhost:8000/dist/css/%7B%7Brtl%7D%7Dstyle.css Not Found

角括号包含在 url 中,这就是 url 中 %7b 的原因,请使用 ngHref 指令

 ng-href="css/{{rtl}}bootstrap.css"

最好使用最终呈现为href属性的ng-href,但前提是ng-href中的表达式被完全解析。

<link rel="stylesheet" ng-href="css/{{rtl}}bootstrap.css">

这也有助于搜索引擎优化。爬网程序不会看到ng-href href属性,因此网络爬虫不会向您的服务器发出其他请求。