I have a webpart that requires jQuery to run. Therefore, in my code I want to check if jQuery is not on the page inject it. I've got down the inject part, but the detection part it where I'm struggling. I tried to the following two things:
- Register script using ScriptLink.Register(). I expected better from this method, but all it did was put inject the script, without even checking if the script exists. So, I registered jQuery in the master page using ScriptLink and then called ScriptLink.Register() to register same script (same name, same path), and SharePoint still registered it twice.
- Then I created a loop to check all controls on the page and check if its a ScriptLink, and then check if it had jQuery. If no scriptlink control had jQuery, then I injected it. I expected this to work, but instead the no jQuery was loaded on the page. This was super-weird.
I'm still diagnosing the issue, but wanted some advice. Maybe there is some other (better) way to accomplish this.
So this is all I want to do: Check if there is jQuery (or any script) registered on the page. If not, then registered it.
I can possibly also use JavaScript, but all my JS files are embedded resources. So, those cannot be loaded using client side code. WebParts don't support WebMethods, so that's a bummer too.
Many thanks for reading this never-ending question and giving a thought to my problem. Much appreciated!
UPDATE: The code I'm using for the loop in step 2. (*Note, as of now it's only checking the page header controls, but it'll probably be the whole page, which will also kill performance) =(
// The code below is bad, but it's a quick write-up, please don't scold me for that. =(
// parse header controls
foreach (var itm in page.Header.Controls)
{
if (itm is ScriptLink)
{
if ((itm as ScriptLink).GetDesignTimeHtml().Contains(keyword) || (itm as ScriptLink).GetDesignTimeHtml().Contains(keyword))
{
containsScript = true;
break;
}
}
}