dotnetnoob
dotnetnoob

Reputation: 11330

Best method of adding this javascript to Asp.Net website?

I have a couple of small javascript functions:

// Show cookie notice
$('#site-cookie-notice').slideDown();

// Hide cookie notice
$('.close-cookie-notice').click(function (e) {

    if (e.preventDefault) {
        e.preventDefault();
    }
    else {
        e.returnValue = false;
    }

    $('#site-cookie-notice').slideUp();
});

The functions are only relevant to a single user control, that appears a maximum of once in a user visit (not at all for returning customers). The rest of the time the control is not rendered.

The above code currently resides in my global.js, inside the document.ready function, so loads every page, however it seems like this is wrong an uneccessary use of resource.

I'd be interested to know if there is a better approach to registering this code on such an adhoc basis.

Upvotes: 0

Views: 52

Answers (2)

ps2goat
ps2goat

Reputation: 8475

Use the ScriptManagerProxy in the user control to reference this script. That will include it on your page without having to have it on all pages.

This requires a ScriptManager or ToolkitScriptManager (if using AjaxControlToolkit) on your master page or content page. You can only have one script manager per entire rendered page.

http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy.aspx

Upvotes: 0

Bernhard Hofmann
Bernhard Hofmann

Reputation: 10391

You can use the ScriptManager class to register scripts in the load of your user control. This can also be used to ensure that the script isn't loaded more than once.

You can use either RegisterClientScriptBlock or RegisterClientScriptInclude depending on whether you want to provide the script in-line or have it in a separate file.

Upvotes: 1

Related Questions