What is @section scripts and what it is used for

前端 未结 4 1356
不知归路
不知归路 2021-01-31 02:21

I have downloaded a chat example from the Microsoft website. I have been following several tutorials but I have never seen the @section script{} before I have done scripts with

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 03:00

    There is also one thing that should be added to the answers above that makes the use of "scripts" section crucial in most cases which is also the only reason for me to use this section.

    That is, it guarantees that scripts will load after all page contents which is essential. By doing this, you actually make sure necessary elements for your JavaScript code have loaded already and also it is a matter of performance.

    To elaborate how it works, I should mention that:

    1. That is a common practice to put the commonly used scripts inside the "_Layout" page to make them accessible among all pages and also prevent their repetition.
    2. All contents of child views are loaded into the _Layout view where @RenderBody() method is called. Except the contents inside @sections of each view.

    When we define "scripts" section inside the footer of the layout for common scripts and then add our scripts of child views inside the "scripts" section of each child view we make sure that these scripts will load after the script of the layout that makes the functions in the _Layout available to the scripts of the child views.

    Otherwise, the scripts of child views would be loaded where RenderBody() method is called, before the common scripts of the _Layout page.

    For Example:

    Inside _Layout:

    @RenderBody()
    
    @RenderSection("Scripts", required: false)

    Inside MyView:

    
    @section Scripts
    {
        
    }
    

提交回复
热议问题