I want to use handlebars on the client side. In my html code I have calls like:
<img src="data/cloud/products/{{key}}/{{images.product.frontal.trans_bg_img}}" alt="">
directly in my index.html.
In javascript I do something like this:
this.emptyPageSource = $("#productdetail").html();
this.productTemplate = Handlebars.compile(this.emptyPageSource);
var html = this.productTemplate(product);
$("#productdetail").html(html);
which works fine. I take the existing piece of html from the dom as a template once, then apply the templating with handlebars and overwrite the old dom entry.
When I load the page, I get a lot of 404 requests, because the browser already tries to load the image resources, even if the templating wasn't invoked yet, due to the JS part.
Is there a way to evade the 404 get requests? (I'm not using angular or something alike - just plain js + jquery)
Thank you in advance Chris
I will try converting #productdetail
element to <script type='text/template' id='productdetail'>
. As in: JSBin
<h1>A Cat</h1>
<script type="text/template" id="productdetail">
<img src="{{image}}" alt="">
</script>
Rest of it
<script>
var product = {
key: '1',
image: 'https://media.giphy.com/media/freTElrZl4zaU/giphy.gif'
}
var emptyPageSource = $("#productdetail").html();
var productTemplate = Handlebars.compile(emptyPageSource);
var html = productTemplate(product);
$("#productdetail").replaceWith(html);
</script>
The browser does not understand text/template
scripts and just ignores its. But we can read the content inside our script tag use it as a template.