简体   繁体   中英

How to correctly place scripts files in ASP.Net MVC Application

I'm new to MVC / .net and currently doing some simple exercises. I have this javascript code where I try to register my service-worker but for some reason, it's not running. I followed all the tutorial that I can find, searched up on this but still, it doesn't work. So I'm at lost here. Thank you for helping.

@RenderSection("pageScripts", required: false)
@section pageScripts{
    <script type="text/javascript" language="javascript">

        console.log('test script');

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.js').
                then(function (registration) {
                    // Registration was successful
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                }).catch(function (err) {
                    // registration failed :(
                    console.log('ServiceWorker registration failed: ', err);
                });
        }

    </script>
}

Assuming the script logic you have written is required by LayOut file you need to replace your code with below:

<script type="text/javascript" language="javascript">

            console.log('test script');

            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/service-worker.js').
                    then(function (registration) {
                        // Registration was successful
                        console.log('ServiceWorker registration successful with scope: ', registration.scope);
                    }).catch(function (err) {
                        // registration failed :(
                        console.log('ServiceWorker registration failed: ', err);
                    });
            }

        </script>
    @RenderSection("pageScripts", required: false) // NOTICE IT HAS COME DOWN

Kindly note that: If you are in Layout file then you DO NOT need to add

@section pageScripts{
}

On a side note, Sequence of adding scripts in your Layout file

    ....   
    ....
   </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("Any Third Party Script") 
    @Scripts.Render("Your own Custom Script file Required By Entire Application")
    <script>
       // ADD ANY Script related to LayOut Page here
        </script>
     @RenderSection("pageScripts", required: false)
</body>
</html>

Now if script is exclusively required by a particular view then..

For example: Index.csthml

...
</div>

@section pageScripts
{
  // Your script logic
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM