I want to start with pages that work without Javascript, then add Javascript fanciness and finally add some bits of Ajax.
This all seems to keep stuff clean, I was very happy with my first experiments with it. Then I ran into the following problem for which I don't see a nice solution. For these 2 example pages:
<!-- /products/ -->
<ul>
<li>
Product A thumbnail
<a href="/details/1/">Details for A</a>
</li>
<li>
Product B thumnail
<a href="/details/2/">Details for B</a>
</li>
</ul>
<!-- /details/<id>/ -->
<script type="text/javascript" src="/details.js/"></script>
show details about the product with the given id
details.js will unobtrusively enhance it
The functionality I want
Use Ajax to dynamically load some of the details for a product on the /products/
page, for example when hovering over the thumbnail. More precisely, fetch and show a simplified version of the /details/<id>/
on the /products/
page.
The unobtrusive implementation
When hovering a photo, make an Ajax request for the href
attribute of the corresponding anchor. The server can respond with the full /details/<id>/
page and a JQuery selector can cut just the interesting parts. Alternatively, the server could see that the request is special and just return the interesting parts. So far so good, easy and clean.
The problem
The /details/<id>/
page is more than just HTML. It also had its own Javascript to make it fancy, therefore I want to reuse that Javascript in the /products/
page. So I want /products/
to fetch not just the HTML from /details/<id>/
but also replicate the Javascript behaviour that is present on the fully fledged /details/<id>/
page.
The only (bad) solution I could think of
Write explicit code to replicate what the browser does when loading a page: fetch /details/<id>/
, look for all <script>
tags, fetch that Javascript, trigger the on load handlers. That's a lot of boilerplate stuff that seems hard to get right. I clearly don't want to write it as the result would be anything but simple.
I also feel like it's the kind of problem that appears very often if you truly stick to unobtrusive Ajax and that there must be a more elegant solution for it.