Get Started!

Quick JavaScript Includes Via ASCXs

Sometimes you don't want to include a JavaScript reference on all sections of a site; you might have some JavaScript that's only needed for a single Control in your site. Here's how to quickly include JavaScript files programatically from the CodeBehind of an ASCX.

The reccomended method of including common JavaScript for all sections of a site is to use the Default.aspx & reference a PreProcessor see this post on Default.aspx for a complete example.

Abstract

The PageBase class, which all NetCanvas aspx inherit from, has a Property aJavaScriptIncludes which is a simple collection of strings, of type List<string>.

The standard NetCanvas HTML for the apsx's includes loops this collection of strings, and includes a JavaScript reference for each item in the collection.

The references to the script files will be appended to the bottom of the <body> as per standard Best Practices.

101 Include

In it's simplest form the following, example ascx CodeBehind would include a CDN copy of jQuery UI :

protected override void initialize(){

  base.initialize();

  oPage.aJavaScriptIncludes.Add(
    "https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"
  );

}

Using a PreProcessor Result

If you have a JavaScript PreProcessor, say my-javascript, that you want to include here's how:

protected override void initialize(){

  base.initialize();

  // Get the path of the current PreProcesor result
  var jsPath = oPage.GetPreProcessedFilePath(
    "my-javascript"
  );

  // Add to the Includes stack
  oPage.aJavaScriptIncludes.Add(
    jsPath
  );

}

Yes, the statement could be written :

  oPage.aJavaScriptIncludes.Add(
    oPage.GetPreProcessedFilePath(
      "my-javascript"
    )
  );

Conclusion

Using these in combination with the recommend method of including common JavaScript it's a relativly trivial task to manage & ensure that any JavaScript, required for a a given page/control, included.

Without the negative impact of bloating the common site-wide JavaScript with logic that might never be used.

Another use-case is role / user based inclusion, there might be scripts that are only applicable to certain users/roles and thus you can programitically control exactly what should or shouldn't be included.