js,css引用顺序设定

2017-12-26  本文已影响0人  Lulus

遇到的困难

在ASP .NET MVC里面,会使用_Layout.cshtml来绘制一些全局的公共页面,以及引用相关的css和js
而在每个独立的页面中,也有自己独立的js
一般来说,希望公共的js放在独立的js之前
css同理

作法

方案1

使用@RenderSection-@section XXX的方法
在_Layout.cshtml里定义一个放置@section里面内容的地方,再在独立页面中使用@section XXX放置相关引用
保证XXX名字相同,则加载的时候,会放置到_Layout.cshtml的对应位置
下面例子中定义了"Styles"和"Scripts"两个section,展示了"Scripts"的使用
_Layout.cshtml

<!DOCTYPE html>
<html>
<head id="Head1">
    <title>
        
    </title>
    <link href="~/css/common/style.css" rel="stylesheet" type="text/css">
    <link href="~/lib/kkpager/kkpager_orange.css" rel="stylesheet" type="text/css">
    <link href="~/lib/swiper/dist/css/swiper.min.css" rel="stylesheet" type="text/css">
    <link href="~/lib/layer/theme/default/layer.css" rel="stylesheet" type="text/css">
    
    @RenderSection("Styles", required: false)
</head>
<body>
    

    @RenderBody()

    <script type="text/javascript" src="~/js/common/jquery.js"></script>
    <script type="text/javascript" src="~/lib/angular/angular.min.js"></script>
    <script type="text/javascript" src="~/lib/kkpager/kkpager.min.js"></script>
    <script type="text/javascript" src="~/lib/swiper/dist/js/swiper.min.js"></script>
    <script type="text/javascript" src="~/lib/layer/layer.js"></script>
    <script type="text/javascript" src="~/js/common/common.js"></script>
    <script type="text/javascript" src="~/js/common/jquery.jslides.js"></script>

    @RenderSection("Scripts", required: false)

</body>
</html>

独立页面中,这样写

@section Scripts
{
    <!--这里的内容会放置在@RenderSection("Scripts", required: false)的位置-->
    <script type="text/javascript" src="~/js/news/index.js"></script>
}

方案2(不推荐)

把公共的js放在Head里面,像这样

<!DOCTYPE html>
<html>
<head id="Head1">
    <title>
        
    </title>
    <link href="~/css/common/style.css" rel="stylesheet" type="text/css">
    <link href="~/lib/kkpager/kkpager_orange.css" rel="stylesheet" type="text/css">
    <link href="~/lib/swiper/dist/css/swiper.min.css" rel="stylesheet" type="text/css">
    <link href="~/lib/layer/theme/default/layer.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="~/js/common/jquery.js"></script>
    <script type="text/javascript" src="~/lib/angular/angular.min.js"></script>
    <script type="text/javascript" src="~/lib/kkpager/kkpager.min.js"></script>
    <script type="text/javascript" src="~/lib/swiper/dist/js/swiper.min.js"></script>
    <script type="text/javascript" src="~/lib/layer/layer.js"></script>
    <script type="text/javascript" src="~/js/common/common.js"></script>
    <script type="text/javascript" src="~/js/common/jquery.jslides.js"></script>
    @RenderSection("Styles", required: false)
</head>
<body>
    

    @RenderBody()

    @RenderSection("Scripts", required: false)

</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读