我怎么能知道,如果一个JavaScript文件已经被包含在顶级页面? [英] How can I know if a javascript file has already been included in a top-level page?

查看:188
本文介绍了我怎么能知道,如果一个JavaScript文件已经被包含在顶级页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件(ASCX),在此用户控件我想用一个.js文件。

I have a user control (ascx), in this user control I wanna use a .js file.

所以,我包括在它的上面。

So I include on top of it.

在另一方面,有时我用这个用户控件,该脚本已经被加载过它的网页。

On the other hand, sometimes I use this user control in a webpage that this script has already been loaded on it before.

我如何作出声明,并使其实际只有当页面中不包含此脚本其他标签?

How can I make a declaration and make it actual only if the page doesn't contain another tag for this script?

推荐答案

当你正在使用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)方法,但它似乎pretty冗余登记为多次尝试注册之前不要做检查抛出异常或导致任何其他错误。

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.

在做检查的客户端是指,假设多个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.

这篇关于我怎么能知道,如果一个JavaScript文件已经被包含在顶级页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆