How to: Add Silverlight to a Web Page by Using JavaScript
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Silverlight.js is a JavaScript helper file that you can reference in your HTML markup. You can call the createObject and createObjectEx functions defined in this file to embed the Silverlight plug-in in a Web page. This topic calls these functions the embedding functions.
Note: |
---|
Silverlight.js depends on browser implementation details that can change between Silverlight releases. For this reason, the use of Silverlight.js is not recommended. However, if you choose to use Silverlight.js, you should periodically check for an updated version from the Silverlight.js page of the MSDN Code Gallery. |
The Silverlight.js embedding functions accept configuration details as input parameters and generate HTML object elements. Using the object element is the recommended embedding technique, and is compatible with all supported browsers. For more information about the object element, see How to: Add Silverlight to a Web Page by Using HTML.
Although using Silverlight.js incurs a maintenance cost, the JavaScript embedding functions provide the following benefits over using the object element directly:
They enable you to programmatically configure a Silverlight plug-in when you embed it, or abstract the configuration details into a separate, shared function.
They are backward compatible with the Silverlight 1.0 createObject and createObjectEx functions.
They enable you to specify a unique identifier for each plug-in that you embed. This is useful when you embed multiple plug-in instances in a single Web page.
This topic describes how to accomplish the following common tasks using the JavaScript embedding functions:
Embed the Silverlight plug-in, specify the application to host, and specify common configuration values.
Specify alternate HTML to display when Silverlight is not installed.
The following procedures explain these tasks by using a createObject function call embedded in a div placeholder element. These examples cannot be used in isolation. At a minimum, they require a reference to the Silverlight.js helper file. You typically also provide additional HTML to ensure cross-browser compatibility.
For a complete HTML example that is cross-browser compatible, see the end of this topic. The complete example also illustrates the difference between the createObject and createobjectEx functions, and shows different ways to use the embedding functions. Note, however, that this example provides only a basic installation and upgrade experience. For more information on improving this experience, see Microsoft Silverlight Installation Experience White Paper and Sample Code.
You can accomplish additional configuration tasks by specifying additional plug-in properties and events when you call the embedding function. For more information, see Silverlight Plug-in Object Reference.
You can accomplish additional installation tasks using the Silverlight.js helper file. For more information, see the Silverlight.js Reference.
Procedures
To embed the plug-in
Use the createObject function and specify parameter values as shown in the following example.
<div id="silverlightControlHost"> <script type="text/javascript"> Silverlight.createObject( "ClientBin/SilverlightApplication1.xap", // source silverlightControlHost, // parent element "slPlugin", // id for generated object element { width: "100%", height: "100%", background: "white", version:"4.0.60310.0" }, // See the event handlers in the full example. { onError: onSLError, onLoad: onSLLoad }, "param1=value1,param2=value2", "context" // context helper for onLoad handler. ); </script> </div>
The first parameter value specifies the Silverlight plug-in Source value. This value is required, and indicates the location and name of your application file. You typically specify a .xap application package in a location relative to the HTML file. For more information about application development and the application package, see Application Model.
The second parameter specifies the HTML element that will host the Silverlight plug-in. In this example, the host element is the parent div element.
The third parameter specifies the HTML DOM id of the generated object element.
The fourth parameter specifies an array of property values. For more information about the available properties, see the Silverlight Plug-in Object Reference.
The width and height properties are required for cross-browser compatibility. You can specify fixed pixel values or percentages relative to the width and height of the parent element. If you use relative sizing, you can respond to plug-in size changes by handling the Content.Resized event. For more information, see Silverlight Plug-in Sizing.
The version property indicates the required version of Silverlight. Users who do not have the required version installed will be shown the default installation image. For more information, see Silverlight Plug-in Versioning.
The fifth parameter specifies an array of event handlers. For an example of the onError and onLoad event handlers, see the end of this topic.
The sixth parameter specifies a string that contains name and value pairs separated by commas. These values are passed to the Application.Startup event. For more information, see How to: Specify and Retrieve Custom Initialization Parameters.
The seventh and last parameter specifies a value that you can use to uniquely identify the generated plug-in instance in an OnLoad event handler. See the end of this topic for a usage example.
To specify alternate HTML to display when Silverlight is not installed
Specify a value for the alt property when you call the createObject function, as shown in the following example.
<div id="silverlightControlHost"> <script type="text/javascript"> var getSilverlightMethodCall = "javascript:Silverlight.getSilverlight(\"4.0.60310.0\");" var installImageUrl = "https://go.microsoft.com/fwlink/?LinkId=161376"; var imageAltText = "Get Microsoft Silverlight"; var altHtml = "<a href='{1}' style='text-decoration: none;'>" + "<img src='{2}' alt='{3}' " + "style='border-style: none'/></a>"; altHtml = altHtml.replace('{1}', getSilverlightMethodCall); altHtml = altHtml.replace('{2}', installImageUrl); altHtml = altHtml.replace('{3}', imageAltText); Silverlight.createObject( "ClientBin/SilverlightApplication1.xap", silverlightControlHost, "slPlugin", { width: "100%", height: "100%", background: "white", alt: altHtml, version: "4.0.60310.0" }, // See the event handlers in the full example. { onError: onSLError, onLoad: onSLLoad }, "param1=value1,param2=value2", "row3"); </script> </div>
This example uses the default install image URI, and uses the Silverlight.js getSilverlight function to provide the default installation experience if the specified version of Silverlight is not installed. This example reproduces the behavior that occurs when you do not specify an alt property value. You can therefore use it as a template for customization.
The install image URI and the getSilverlight function rely on server-side browser detection to provide the correct version of the installation image and installer. If the user's browser is not supported, clicking the image causes the browser to open the Silverlight Requirements page.
You can provide arbitrarily complex alternate HTML in order to integrate the Silverlight install experience with your Web page.
Silverlight.js provides additional functionality for improving the installation experience. This functionality includes automatic browser refresh after new installations so that the Silverlight plug-in can immediately load and display your application. You can also determine whether an upgrade followed by a browser restart is required, and display a message to the user.
For more information, see the Microsoft Silverlight Installation Experience White Paper and Sample Code and the Silverlight.js Reference.
Example
Description
The following code example provides a complete HTML page that uses the Silverlight.js file. It displays a blue background and embeds four Silverlight plug-in controls in the cells of a table. The blue background enables you to test this example in Visual Studio without having to modify the default application code. The default user interface uses a white background, which appears distinct against the blue background of the host Web page.
This example demonstrates the following ways of using the embedding functions:
Using the return value of an embedding function to set the innerHTML property of an HTML element. See the window.onload handler in the example.
Wrapping an embedding function in another function to encapsulate a common configuration. See the embedSilverlight function in the example.
Calling createObject or createObjectEx directly from within an HTML element that will host the plug-in. See the sl3Host and sl4Host elements in the example.
Because this example embeds multiple plug-in instances, only one of them is configured to display an installation experience when Silverlight is not available. To prevent the default installation experience, all plug-in instances except the first one are given a non-empty alt property value. The alt value that is used specifies an HTML comment so that nothing is displayed.
In this example, each Silverlight plug-in is given a unique id and userContext value. The OnLoad event handler uses these values to update the browser status bar, which indicates the load order.
This example uses a JavaScript function to handle the plug-in's OnError event, but leaves the implementation empty. For the default implementation generated by Visual Studio, see How to: Add Silverlight to a Web Page by Using HTML. A JavaScript error handler is useful during debugging, but you typically remove it when you deploy your application. For more information about the errors that you can handle in JavaScript, see Error Handling.
The iframe element and other additions to the HTML help ensure cross-browser compatibility. The presence of the iframe prevents the Safari browser from caching the page. Safari caching prevents the Silverlight plug-in from reloading when the user navigates back to a previously-visited Silverlight page. For more information, see the Safari Developer FAQ.
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- saved from url=(0014)about:internet -->
<head>
<title>EmbeddingWithJS</title>
<style type="text/css">
html, body {
height: 100%;
overflow: auto;
}
body {
background: blue;
padding: 0;
margin: 0;
}
</style>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript">
window.onload = function() {
sl1Host.innerHTML = embedSilverlight(null, "sl1", "row1");
}
function embedSilverlight(parentElement, pluginId, userContext) {
var altHtml = pluginId == "sl1" ? null : "<!--not installed-->";
return Silverlight.createObject("ClientBin/EmbeddingWithJS.xap",
parentElement, pluginId,
{
width: "200", height: "50",
background: "white", alt: altHtml,
version:"4.0.60310.0", autoUpgrade:true
},
{ onError: onSLError, onLoad: onSLLoad },
"param1=value1,param2=value2", userContext);
}
function onSLLoad(plugIn, userContext, sender) {
window.status +=
plugIn.id + " loaded into " + userContext + ". ";
}
function onSLError(sender, args) {
// Display error message.
}
</script>
</head>
<body>
<table>
<tr>
<td id="sl1Host"/>
</tr>
<tr>
<td id="sl2Host">
<script type="text/javascript">
embedSilverlight(sl2Host, "sl2", "row2");
</script>
</td>
</tr>
<tr>
<td id="sl3Host">
<script type="text/javascript">
Silverlight.createObject(
"ClientBin/EmbeddingWithJS.xap", sl3Host, "sl3",
{
width: "200", height: "50",
background: "white", alt: "<!--not installed-->",
version: "4.0.60310.0"
},
{ onError: onSLError, onLoad: onSLLoad },
"param1=value1,param2=value2", "row3");
</script>
</td>
</tr>
<tr>
<td id="sl4Host">
<script type="text/javascript">
Silverlight.createObjectEx({
source: "ClientBin/EmbeddingWithJS.xap",
parentElement: sl4Host,
id: "sl4",
properties: {
width: "200",
height: "50",
background: "white",
alt: "<!--not installed-->",
version: "4.0.60310.0" },
events: {
onError: onSLError,
onLoad: onSLLoad },
initParams: "param1=value1,param2=value2",
context: "row4"
});
</script>
</td>
</tr>
</table>
<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</body>
</html>
Comments
This example is a modified version of the HTML test page generated by Visual Studio when you create a new project and add a Web for hosting the control. A Web project is useful when you are developing with JavaScript for the following reasons:
You can disable Silverlight debugging in order to debug JavaScript instead. For more information, see Debugging Overview.
The Web project template provides an HTML test page that you can add JavaScript code to. Note, however, that the default start page is the ASPX test page. To set the HTML page as the start page, right-click it in Solution Explorer and then select Set As Start Page.
For information about Silverlight projects in Visual Studio, see How to: Create a New Silverlight Project.
See Also