6

I've been working in asp.net webforms and I've been making a UserControl that depends on a small bit of javascript which is in an external file.

I want to be able to put a reference to the javascript inside the UserControl to ensure that it gets loaded on the page, but the problem is that the UserControl can appear multiple times on a page so I only want the script to be loaded with the first instance of the UserControl.

Is there an easy way to do this in ASP.NET Webforms?

2 Answers 2

10

Use the ClientScriptManager's RegisterClientScript() methods to handle this. In your case, since you're including the script from an external file, use RegisterClientScriptInclude().

Alternately, if you're using UpdatePanels, use ScriptManager's equivalent Register...() methods.

Sign up to request clarification or add additional context in comments.

Comments

0

You could also handle this issue in the JS file itself, if you control its content.

var myObj = myObj || {};  // Variable to namespace your work

// Make sure we do our work only once
if (!(myObj.token)) {

    // do our work here...

    myObj.token = {};  // this ensure we won't enter the if block the next time

}

2 Comments

I'm not sure how this will ensure a script file only gets loaded once? It'll check if a script has been loaded, but could you explain how it will make sure the script isn't loaded multiple times?
Yes, technically the script is included twice in the page DOM and will be processed twice by the browser. The difference is that, on the 2nd pass, nothing happens because myObj.token has already been defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.