在ASP.NET MVC中加载JavaScript的最佳方法是什么?

时间:2022-08-26 20:49:41

I'm new in ASP.NET MVC world and I want to know which way is the best to load JavaScript codes into the project:

我是ASP.NET MVC世界的新手,我想知道哪种方式最好将JavaScript代码加载到项目中:

  1. using script tag directly in the page.

    直接在页面中使用脚本标记。

  2. using BundleCollection class to add scripts.

    使用BundleCollection类添加脚本。

  3. using jQuery.getScript method to load the scripts dynamically.

    使用jQuery.getScript方法动态加载脚本。

and want to know what is the difference between them.

并想知道它们之间有什么区别。

1 个解决方案

#1


2  

It all depends upon the usage.

这一切都取决于用法。

If you want to avoid waiting for all the javascript to load before your page fires the ready event, then you may use jQuery.getScript.

如果你想避免在页面触发ready事件之前等待加载所有的javascript,那么你可以使用jQuery.getScript。

Using the script tag directly will ensure that the script is available and executed before the browser parser proceeds to the next line.

直接使用脚本标记将确保脚本在浏览器解析器进入下一行之前可用并执行。

Lastly, in ASP.NET, using the BundleCollection can help you optimise your JS, in a way that it allows you to bundle, compress and even minify the content before serving. This can result in quicker loading times if you have a lot of JS files on your page.

最后,在ASP.NET中,使用BundleCollection可以帮助您优化JS,使其能够在服务之前捆绑,压缩甚至缩小内容。如果您的页面上有大量JS文件,这可能会加快加载时间。

#1


2  

It all depends upon the usage.

这一切都取决于用法。

If you want to avoid waiting for all the javascript to load before your page fires the ready event, then you may use jQuery.getScript.

如果你想避免在页面触发ready事件之前等待加载所有的javascript,那么你可以使用jQuery.getScript。

Using the script tag directly will ensure that the script is available and executed before the browser parser proceeds to the next line.

直接使用脚本标记将确保脚本在浏览器解析器进入下一行之前可用并执行。

Lastly, in ASP.NET, using the BundleCollection can help you optimise your JS, in a way that it allows you to bundle, compress and even minify the content before serving. This can result in quicker loading times if you have a lot of JS files on your page.

最后,在ASP.NET中,使用BundleCollection可以帮助您优化JS,使其能够在服务之前捆绑,压缩甚至缩小内容。如果您的页面上有大量JS文件,这可能会加快加载时间。