Search code examples
javascriptrazor-pages

Getting Razor page name for conditional loading of script in layout page


I need to conditionally load a script in a the layout page of a Razor pages application (the script needs to be loaded after other scripts have loaded but assumes the existence of elements only on one page).

I want to use something like

@{
   if (Page.Name == "page_name") {

      <script src="~/js/myscript.js"></script>
   }
}

but can find no method for getting the page name.

Can anyone please recommend a way to do this?


Solution

  • The way to do this is to create a new section in the layout, below the existing scripts and then target that from the page that utilises the script:

    Layout:

    @RenderSection("Scripts", false)
    @RenderSection("ExtraScripts", false)
    

    Then in the page that needs to use the script:

    @section ExtraScripts{
        <script src="~/js/myscripts.js"></script>
    }
    

    Sections: https://www.learnrazorpages.com/razor-pages/files/layout#sections

    If you want the contents of myscripts to load after the body has loaded, put it in a jQuery ready function, or a DomContentLoaded event handler.

    DomContentLoaded : https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event