包括JavaScript在页面底部,从管窥 [英] Including JavaScript at bottom of page, from Partial Views

查看:121
本文介绍了包括JavaScript在页面底部,从管窥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个JavaScript幻灯片显示在局部视图...

Let's say I have a javascript slide-show in a partial view...

_Slideshow.cshtml:

@{
    ViewBag.Title = "Slide Show";
}
<div id="slides">
</div>
<script src="js/slides.min.jquery.js"></script>
<script type="text/javascript">
$(function(){
    $('#slides').slides({
        // slide show configuration...
    });
});
</script>

不过,我想成为一个好一点的Web开发人员,并确保我所有的脚本走在页面的底部。所以,我会让我的* _Layout.cshtml *页看起来是这样的:

But I want to be a good little web developer, and make sure all of my scripts go at the bottom of the page. So I'll make my *_Layout.cshtml* page look like this:

_Layout.cshtml:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/css/global.css")" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="wrapper">
    @RenderBody
    </div>
    <!-- Being a good little web developer, I include my scripts at the BOTTOM, yay!
    -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
</body>
</html>

不过,嗯哦!现在我该怎么办,因为我的幻灯片显示的脚本中我的jQuery列入结束了?它不会是一个大问题,如果我想我的幻灯片每一页上,但我只想幻灯片局部视图要在某个页面上呈现,并....我希望我的脚本,以在底部!怎么办?

But UH OH! What do I do now, because my slide show script ends up above my jQuery inclusion?! It wouldn't be a big deal if I wanted my slide show on every page, but I only want the slide show partial view to be rendered on a certain page, and.... I WANT MY SCRIPTS AT THE BOTTOM! What to do?

推荐答案

您可以在您的页面布局定义的一部分以这样的脚本:

You could define a section in your layout page for the scripts like this:

<body>
    <div id="wrapper">
    @RenderBody
    </div>
    <!-- Being a good little web developer, I include my scripts at the BOTTOM, yay!
    -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
    @RenderSection("myScripts")
</body>

然后在你的页面,你定义什么去该节:

Then on your pages you define what goes in that section:

@{
    ViewBag.Title = "Slide Show";
}
<div id="slides">
</div>
@section myScripts { //put your scripts here
    <script src="js/slides.min.jquery.js"></script>
    <script type="text/javascript">
    $(function(){
        $('#slides').slides({
            // slide show configuration...
        });
    });
    </script>
}

然后,当页面呈现,将采取一切在您部分并把它添加到它应该继续布局页(在这种情况下,在底部)。

Then when the page renders, it will take everything in your section and add it to where it is supposed to go on your layout page (in this case, at the bottom).

这篇关于包括JavaScript在页面底部,从管窥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆