Extending the HTML trick: using actual images

Eric Sevareid famously said that the chief cause of problems is solutions. The same applies to the HTML trick I blogged about yesterday. As soon as you solve the problem of using HTML directly in your control add-ins, another problem arises: what do you do with actual images your control add-in includes?

This post explains how to solve that problem, and how to make it possible for your control add-in to both use HTML for defining UI and use relative control add-in paths to images.

Let’s dig in.

Imagine you had a control add-in with this script:

… that shows this:

Now, you fix this by applying the image trick, and refactor all this as HTML:

… and then load with this script:

… the results will be less than impressive:

Where is the problem? It’s simple: your image source URLs.

The image URLs you defined in HTML are relative, and this means they are relative to your entire URL. In my case, the URL is http://desktop-tfdoknj:8080/DynamicsNAV110/Webclient/ so the relative image URL is http://desktop-tfdoknj:8080/DynamicsNAV110/Webclient/Demo/Images/accept.png (and reject.png), neither of which – guess what? – doesn’t exist at the path that this URL resolves to. If you read the yesterday’s post carefully, you know that all images are extracted to a “random” location (random only because you don’t know its exact absolute path in advance), and that’s the reason why you need the GetImageResource method in the first place: to resolve your relative control add-in path to the absolute server path of an image (or resource).

The solution

The solution is actually far simpler than it may seem at first. In theory, after you inject your HTML into the page, you need to locate all of the <img> tags, read their src attributes, and replace them with URLs that you remap using the GetImageResource method.

In practice, it translates to:

I used jQuery for this only because I am already using jQuery, but if you want, you can simply do this with pure DOM:

That’s it. Simple, and easy.

As always, you can find the demo code on my github: https://github.com/vjekob/controladdin-html

It’s the same repository as from my HTML trick post, however there are four new branches:

  • Branch “images-1”: the demo without the HTML trick
  • Branch “images-2”: the demo with the HTML trick applied, but with image src problem
  • Branch “images-3”: fixes the image src problem
  • Branch “images-4”: uses DOM instead of jQuery to fix the src problem

Thanks for the attention, and stay tuned for more control add-in and JavaScript tips and tricks. There’s a lot more to come!

Vjeko

Vjeko has been writing code for living since 1995, and he has shared his knowledge and experience in presentations, articles, blogs, and elsewhere since 2002. Hopelessly curious, passionate about technology, avid language learner no matter human or computer.

This Post Has 3 Comments

Leave a Reply