Adding lifecyle functions to a Mashup widget to load and unload the widget’s CSS 
|
Currently IBM Mashup Centre will load all the files listed as <iw:resource> when the widget gets displayed. But, when the widget gets disposed of, the CSS files that have been loaded for the widget, don’t get removed. |
ShowTable of Contents
To avoid any possible problem with existing CSS files from other widgets overwriting each other, you can add two small functions to the widget’s code, and let the widget control the load and unload of its CSS file(s). These functions override the common usage of the ‘target’ attribute in the link tag, as its role isn’t supported by any browser. By placing the widgetId as the ‘target’ attribute’s value, we can identify that the link was added by a particular widget, which means we can easily remove it when needed. Adding lifecycle functions 1. Make sure that you do not list the CSS file(s) as in the widget’s xml file. Comment them out if you do.
2. Edit the widget’s javascript file and add the 2 following functions in the widget’s code. In this example the CSS file is found in /styles/myWidget.css, change this as needed for your own widget.
loadWidgetStyleSheet: function(){
var link = dojo.doc.createElement('link');
link.rel = 'stylesheet';
link.href = this.iContext.io.rewriteURI("/styles") +'/myWidget.css';
link.type = 'text/css';
link.target = this.WID;
dojo.doc.getElementsByTagName('head')[0].appendChild(link);
},
unloadWidgetStyleSheet: function() {
var list = dojo.doc.getElementsByTagName('link');
for (var i=list.length; i >= 0; i--) {
if (list[i] && list[i].getAttribute('target') == this.WID) {
list[i].parentNode.removeChild(list[i]);
}
}
},
3. Call the new functions respectively from onLoad():
onLoad: function() {
this.WID = "_"+this.iContext.widgetId+"_";
// load my CSS
this.loadWidgetStyleSheet();
... (load the rest of the widget) ...
},
... and from onUnload():
onUnload(): function() {
// remove my CSS
this.unloadWidgetStyleSheet();
... (do more clean up) ...
},
You should now see your CSS file(s) get unloaded when your widget is being disposed of. By controlling the loading and unloading of the widget’s CSS file(s), the widget’s author is making sure that the widget’s code and stylesheet(s) will not linger in the Mashup environment after the widget has been destroyed.
|
|
|
|
| Version 5 |
July 13, 2011 |
5:13:21 AM |
by Florence Adam  |
|
|