Controlling the order of Script Resources (e.g. Jquery) with a Custom ViewRootRenderer
When loading Client Side Javascript libraries in XPages, sometimes the order that the libraries are ‘encoded’ (or written in HTML) in the <head> tag is important.
For example jQuery and some of it’s plugins can have some issues if Dojo is encoded first.
By default in XPages you don’t have too much say in what is written out first, a nifty workaround for this has been shared by Sven Hasselbach (here and here) which utilises the lesser known <xp:headTag> tag. This workaround ensures the specified libraries will be encoded before all the normal XPages resources are encoded.
UPDATE!! It turns out that Sven made a solution like this a couple of years after those original posts! I just didn’t see it because all my googling took me to the original posts. So check out his solution as well as it allows a bit more control.
There are only 2 downsides to this method and they are not too major.
- You must have resource aggregation turned on
- You can’t use a theme to specify the resources
I wanted to come up with another solution because sometimes I like to turn resource aggregation off while developing, and also I would prefer to specify these resources in a theme instead of on individual Xpages, or alternatively adding the resources programatically with java.
Developing the solution
In the end, the actual solution is not too complicated. But, getting to that point is always the tricky part so I will explain how I went about it, and at the end you can install to your own applications and modify if you like.
The starting point is to ask, “Well how does XPages actually write out these <script> / <link> tags anyway?”. The answer is that it does so using a Renderer.
At the very Root of your XPages component tree is the UIViewRoot (corresponding to the <xp:view> tag.
Just like all your other components on your xpage (e.g. panel, inputText, viewPanel etc.) have renderers, so too does the UIViewRoot component, and it is this renderer that is responsible for generating the surrounding <html><head></head><body> tags.
We don’t want to re invent the wheel, we just want to change it’s behaviour ever so slightly, so our plan is to extend the existing view root renderer, override one of it’s methods and register our new renderer in place of the other one.
Creating our ViewRootRenderer
The default View Renderer for XPages is of the class com.ibm.xsp.renderkit.html_basic.ViewRootRendererEx2 So we are going to extend that one and see what we can do with it.
I create new Java class in the NSF
1 2 3 4 5 6 7 8 9 |
package com.gregorbyte.xsp.ViewRootRenderer; import com.ibm.xsp.renderkit.html_basic.ViewRootRendererEx2; public class ViewRootRenderer extends ViewRootRendererEx2 { } |
Now which method to override? Lets have at the ones we can and see which might be it.
We can use the Source => Override/Implement Methods dialog to show us some candidates.
Encode Resources List, sounds pretty good. All Stylesheets, scripts etc. are known as ‘Resources’ so this should be what we are looking for. Let’s override that method and throw in some testing code to see if we are on the right track.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.gregorbyte.xsp.ViewRootRenderer; import java.io.IOException; import java.util.List; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import com.ibm.xsp.component.UIViewRootEx; import com.ibm.xsp.renderkit.html_basic.ViewRootRendererEx2; import com.ibm.xsp.resource.Resource; public class ViewRootRenderer extends ViewRootRendererEx2 { @Override protected void encodeResourcesList(FacesContext context, UIViewRootEx viewRoot, ResponseWriter writer, List<Resource> resources) throws IOException { // Write a comment so we can see in the generated HTML we are in the right spot writer.writeComment("Before Resources"); writer.write("\n"); // new line super.encodeResourcesList(context, viewRoot, writer, resources); // Write a comment so we can see in the generated HTML we are in the right spot writer.writeComment("After Resources"); writer.write("\n"); // new line } } |
Next thing to do is register our Renderer, and then tell XPages to Use it for our view root.
Register the Renderer
To do this we need to tell XPages (via faces config)
- The Component family that our renderer is available to
- What name do we refer to our renderer (renderer-type)
- What is the Java Class of this renderer
The component family can be found with a little debugging, we can choose whatever name we want for renderer-type, and we know the java class because we just created it!
our faces config entry is like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="UTF-8"?> <faces-config> <!--AUTOGEN-START-BUILDER: Automatically generated by IBM Domino Designer. Do not modify.--> <!--AUTOGEN-END-BUILDER: End of automatically generated section--> <render-kit> <renderer> <component-family>javax.faces.ViewRoot</component-family> <renderer-type>com.gregorbyte.xsp.ViewRoot</renderer-type> <renderer-class>com.gregorbyte.xsp.ViewRootRenderer.ViewRootRenderer</renderer-class> </renderer> </render-kit> </faces-config> |
Tell Xpages to use our renderer
Here we have 3 options!
- Specify on an XPage by XPage basis, some XPages use ours some don’t
- Use a theme to set the ViewRootRenderer for every page in the application
- Override the default renderer directly in faces-config
Option 1: Specify on a Page by Page basis
To do this we find the root <xp:view> tag of our xpage, and set the rendererType attribute there
1 2 3 4 5 |
<?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core" rendererType="com.gregorbyte.xsp.ViewRoot"> </xp:view> |
Although this works, it is the least desirable option, but it is a good technique if you quickly want to change a renderer of a single control.
Since the whole point of this solution is to do it once and for all let’s move on to the next option instead.
Option 2: Use a Theme to set the ViewRootRenderer for every XPage
This is a better option, in the theme we are basically saying to xpages, whenever you find a <xp:view> set the rendererType property to our rendererType (just as we did manually above).
Below is the entry to put in the Theme, and be sure to have your theme selected for your application.
1 2 3 4 5 6 7 8 9 10 11 |
<theme extends="webstandard" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="platform:/plugin/com.ibm.designer.domino.stylekits/schema/stylekit.xsd"> <control> <name>ViewRoot</name> <property> <name>rendererType</name> <value>com.gregorbyte.xsp.ViewRoot</value> </property> </control> </theme> |
Option 3: Override the default renderer
This is another way, where you ‘hijack’ the rendererType that already exists (com.ibm.xsp.ViewRootEx). This way whenever XPages tries to find the IBM renderer, it will find ours instead.
To do this we would specify IBM’s renderer type instead of the one that we created.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="UTF-8"?> <faces-config> <render-kit> <renderer> <component-family>javax.faces.ViewRoot</component-family> <!-- <renderer-type>com.gregorbyte.xsp.ViewRoot</renderer-type>--> <renderer-type>com.ibm.xsp.ViewRootEx</renderer-type> <renderer-class>com.gregorbyte.xsp.ViewRootRenderer.ViewRootRenderer</renderer-class> </renderer> </render-kit> <!--AUTOGEN-START-BUILDER: Automatically generated by IBM Domino Designer. Do not modify.--> <!--AUTOGEN-END-BUILDER: End of automatically generated section--> </faces-config> |
Which method to use is up to you but I prefer option 2 as the intention is clearest.
Check that our renderer is being used
So to check we are using our renderer we would expect to see the comments that we writing in our encodeResourceList method to appear in the generated HTML. Lets do that now by using the view-source function in our browser.
Great! So this means we are able to control what is written out at these spots.
What to do next?
So we know we can write whatever we want at these points in the <head> tag. We could go the cheap and nasty route and just write out the script tags directly from our renderer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
@Override protected void encodeResourcesList(FacesContext context, UIViewRootEx viewRoot, ResponseWriter writer, List<Resource> resources) throws IOException { // Write a comment so we can see in the generated HTML we are in the right spot writer.writeComment("Before Resources"); writer.write("\n"); // new line writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.writeAttribute("src", "js/itsfiveoclock.js", null); writer.endElement("script"); writer.write("\n"); // Write a comment so we can see in the generated HTML we are in the right spot writer.writeComment("Start Normal Resources"); writer.write("\n"); // new line super.encodeResourcesList(context, viewRoot, writer, resources); // Write a comment so we can see in the generated HTML we are in the right spot writer.writeComment("After Resources"); writer.write("\n"); // new line } |
and this does the job, but it is not a super flexible solution as it dose not allow for customisation on a XPage by XPage basis, i.e. all XPages will have the same.
So we need some sort of test to identify:
- which resources should be at the top
- which should be at the bottom
- which should be left to normal (and free to participate in resource aggregation if they like!)
Firstly I will try to make 2 resources that are specified on an XPage to appear in the ‘before’ and ‘after’ sections, and then we will do one from a theme.
Because the ScriptResource implements the FacesAttrObject interface, it can have child ‘attr’ tags that you can specify to be whatever you want. Other resources like the StyleSheetResource also can do this too.
I will utilise this and specify my own ‘encode-position’ attribute that I can use later in the renderer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="UTF-8"?> <xp:view xmlns:xp="http://www.ibm.com/xsp/core"> <xp:this.resources> <xp:script src="js/loadedfrompagebefore.js" clientSide="true"> <xp:this.attrs> <xp:attr name="encode-position" value="before"></xp:attr> </xp:this.attrs> </xp:script> <xp:script src="js/loadedfrompageafter.js" clientSide="true"> <xp:this.attrs> <xp:attr name="encode-position" value="after"></xp:attr> </xp:this.attrs> </xp:script> </xp:this.resources> </xp:view> |
Now in the Renderer we add a bit more logic.
We make a method that will inspect a resource to determine if it should be before, after or normal, based on the encode-position attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* * This method will inspect a Resource and return whether it should be before * after or normal (null) */ private String getPosition(Resource resource) { // Your logic for choosing position goes here! // This test is to see if the resource has a child 'attr' tag which // specifies the encode-position of before or aftre if (resource instanceof FacesAttrsObject) { FacesAttrsObject o = (FacesAttrsObject) resource; if (o.getAttrs() != null) { for (Attr attr : o.getAttrs()) { if (StringUtil.equals(attr.getName(), "encode-position")) { return attr.getValue(); } } } } // None of our tests matched so we just return null return null; } |
And then in our encodeResourceLists, we process the page resources into 3 lists, the ones to render before, the ones to render normally (possibly aggregated if that is set) and the ones to render after.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
@Override protected void encodeResourcesList(FacesContext context, UIViewRootEx viewRoot, ResponseWriter writer, List<Resource> resources) throws IOException { // Create 3 Lists of Resources List<Resource> before = new ArrayList<Resource>(); List<Resource> normal = new ArrayList<Resource>(); List<Resource> after = new ArrayList<Resource>(); // Process the resources into our new lists for (Resource resource : resources) { String position = getPosition(resource); if (StringUtil.equals(position, "before")) { before.add(resource); } else if (StringUtil.equals(position, "after")) { after.add(resource); } else { normal.add(resource); } } // Write a comment so we can see in the generated HTML we are in the // right spot writer.writeComment("Before Resources"); writer.write("\n"); // new line // Encode Resources manually, note we don't pass them to the super // method as we don't want them to be aggregated for (Resource resource : before) { encodeResource(context, viewRoot, writer, resource); } // Write a comment so we can see in the generated HTML we are in the // right spot writer.writeComment("Start Normal Resources"); writer.write("\n"); // new line super.encodeResourcesList(context, viewRoot, writer, normal); // Write a comment so we can see in the generated HTML we are in the // right spot writer.writeComment("After Resources"); writer.write("\n"); // new line // Encode Resources manually, note we don't pass them to the super // method as we don't want them to be aggregated for (Resource resource : before) { encodeResource(context, viewRoot, writer, resource); } } |
Ok, lets check out html and see if it worked…
Woohoo, so that’s the good news, the bad news is this won’t work from a theme, because we can’t utilise the attr’s functionality from theme. We will have to think of something else.
My solution is a bit of a hack in itself, but I am going to temporarily hijack the ‘type’ property of a script resource with some extra information, so instead of ‘type/javascript’ I will put ‘type/javascript/before’ or ‘type/javascript/after’.
Then in the renderer, I will check for this, and then fix it up (restore it back to ‘type/javascript’ so it will be correct when renderered) and attach the ‘Attr’ at that point so that any subsequent tests will use the attr instead to determine before or after.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
/* * This method will inspect a Resource and return whether it should be on * top or bottom or normal (null) */ private String getPosition(Resource resource) { // Your logic for choosing position goes here! // This test is to see if the resource has a child 'attr' tag which // specifies the encode-position of before or aftre if (resource instanceof FacesAttrsObject) { FacesAttrsObject o = (FacesAttrsObject) resource; if (o.getAttrs() != null) { for (Attr attr : o.getAttrs()) { if (StringUtil.equals(attr.getName(), "encode-position")) { return attr.getValue(); } } } } if (resource instanceof ScriptResource) { // Cast it to be a ScriptResource so we can access it as such ScriptResource sr = (ScriptResource) resource; String type = sr.getType(); if (StringUtil.isNotEmpty(type)) { if (type.endsWith("/before")) { // Fix Up the Type sr.setType(type.replace("/before", "")); // Add an attribute instead so that next time it is check it // will use that method sr.addAttr(new Attr("encode-position", "before")); return "before"; } else if (type.endsWith("/after")) { // Fix Up the Type sr.setType(type.replace("/after", "")); // Add an attribute instead so that next time it is check it // will use that method sr.addAttr(new Attr("encode-position", "after")); return "after"; } } } else if (resource instanceof StyleSheetResource) { StyleSheetResource ssr = (StyleSheetResource) resource; // You could do the same type of thing here for stylesheet } else if (resource instanceof LinkResource) { LinkResource lr = (LinkResource) resource; // You could do the same type of thing here for Link Resource //maybe even use something like title or Styleclass instead //lr.getStyleClass(); //lr.getTitle(); } // None of our tests matched so we just return null return null; } |
Lets add some scripts to our theme with this new convention of added /after or /before
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<theme extends="webstandard" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="platform:/plugin/com.ibm.designer.domino.stylekits/schema/stylekit.xsd"> <resources> <script src="js/loadfromthemebefore.js" clientSide="true" type="text/javascript/before"/> <script src="js/loadfromthemeafter.js" clientSide="true" type="text/javascript/after"/> </resources> <control> <name>ViewRoot</name> <property> <name>rendererType</name> <value>com.gregorbyte.xsp.ViewRoot</value> </property> </control> </theme> |
and check our html to see if it worked!
Conclusion
I hope this has shown how you can extend and modify the behaviour of XPages. In this case to solve a common problem that I’m sure many have faced.
I have put these example files in a github repository, let me know if any questions / problems!
Even if you don’t have a need this script before /after business, I hope you got something out of this anyway!
http://hasselba.ch/blog/?p=2070
😉
Haha I had not seen that at all!
I was thinking to myself, “I wonder why Sven didn’t bother to do this?” 🙂
I have updated my post with a link to your solution!
Now I wish that I had blogged about something else 😐