且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何判断JavaScript文件是否已包含在ASP.NET页面中?

更新时间:2023-10-29 10:32:16

当您使用asp.net时,检查服务器端是有意义的,因为这将是您选择添加对javascript文件的引用的位置。从.ascx文件中,您可以注册以下内容:

As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:

this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);

...从您的页面直接调用ClientScript对象:

... from your page you just call the ClientScript object directly:

ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);

'GlobalUniqueKey'可以是任何字符串(我也使用javascript文件的url)

The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)

如果您尝试使用相同的键字符串注册脚本,则它不会执行任何操作。因此,如果您在自己的页面,控件或其他任何地方调用此选项,则最终只会在页面中显示一个引用。这样做的好处是,您可以在页面上拥有多个控件实例,即使它们都尝试注册相同的脚本,也只能执行最多一次。并且他们都不需要担心脚本已经注册。

If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.

有一个'IsClientScriptIncludeRegistered(stringkey)'方法,您可以使用它来查看脚本是否已经已被包含在该密钥下但在注册之前进行该检查似乎非常多余,因为多次尝试注册不会抛出异常或导致任何其他错误。

There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.

执行检查客户端-side意味着,假设浏览器缓存了多个javascript引用(它们可能不是),您仍然有多个标记,每个标记的顶部会导致一些javascript运行。如果您在页面上有20个控件实例,则可能会出现严重问题。

Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues.