In ASP.NET Core MVC it is possible to define a script section for a page like this:
@section scripts {
Generally this is a bad idea because you aren't bundling/minifying your scripts.
@ErikPhilips that not true, imagine that i want a specific javascript code that only run in that partial. why should i bundle it and import all over the application? And for minifying, i can create my typescript file minifyied and import it on the partial inside my script block.
imagine that i want a specific javascript code that only run in that partial.
The script won't only run in that partial it will run for the entire page. It's client side code delivered in a single http call (assuming normal usage because you haven't specified anything else). Consider the partial:
@Model SomeModel
Not reusable because all components same page will be the same width regardless of model.
Instead you can create a single script file and use data-* attributes to store configuration information and let the the single script figure it out (like many MANY libraries do, for example bootstrap):
then in the single script file:
$(document).ready(function(){
$('.my-component').each(function(){
var $this = $(this);
var config = $this.data('config');
$this.css("width", config.width);
$this.css("height", config.height);
});
});
why should i bundle it
Because then it's cached by the browser automatically. That means less to download every instance. Consider the following:
Every time the client visits any page, they have to download probably the same exact code every time, possibly multiple times per page. That takes up both client bandwidth and server bandwidth that is not necessary.
and import all over the application?
You import it once, either globally or maybe once in a specific layout. Because after the first time, it's cached.
And for minifying, i can create my typescript file minifyied and import it on the partial inside my script block.
Then why have script in the partial at all.
Recommended Reading: Decoupling Your HTML, CSS, and JavaScript
- 热议问题