The following class helps to pack html javascript blocks and to deliver it at the same time with the Silverlight application. The script code can be placed either into the xap-packet or into the assembly like an embedded resource.

This approach allows you write Silverlight components in isolated modules form including all the required logic inside the module. It decreases the amount of files requiring installation with the final component.

The program (please see the attachment) was written as the service for SCAB (Silverlight Composite UI). If you do not use this platform please comment ScriptManagerModule class.

Elisy.Scab.Services.ScriptManager class description

The ScriptManager class provides scripts registering and has 2 methods:

  • HtmlElement AddBlock(string id, string script) creates <script> html element on the page and includes javascript block into it.
  • HtmlElement AddInclude(string id, string url) creates <script> html element on the page and sets src attribute as the url.

Both methods return element reference. Id (not required) is the identifier written into the ID attribute.

Direct call examples

sm.AddBlock("script123", "alert('Java script was builded by Scab and is running... ');");
sm.AddInclude ("", "http://code.elisy.net/somescript.js");

Examples of the script blocks packaging

  1. Create file Script.js or download it from post attachment;
  2. Connect the file into the Silverligt project setting the Embedded Resource property for this file;
  3. Call the method AddBlock using the following template (the original project name is Elisy.Scab.Ut1):
    ScriptManager sm = new ScriptManager();
    Stream stream = this.GetType().Assembly.GetManifestResourceStream("Elisy.Scab.Ut1.Script.js");
    String script = new StreamReader(stream).ReadToEnd();
    sm.AddBlock("", script);

The result of article description you can see at code.elisy.net

ScriptManager.cs (2.68 kb)

Script.js (181.00 bytes)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5