Issue
For context: My application has a scheduler and I want to display multiple appointment blocks (say a div as childs an image, text and a button), but this question can also be applicable for let's say product catalogs. What is the best practice for building the HTML content for those blocks?
In my search I found multiple options, for example (with pseudo code)
Build line by line in jQuery
$('<div />').append($('<img />')).append($('<p />').append($('<button />'));
Personally I found this option to become quite ugly once the block contains more than 3-5 elements, because the code started to span more than a full page of scrolling and became unreadable (but this could also be because of my poor coding skills).
Retrieve HTML page via Ajax/Load
<div>
<img><p></p><button></button>
</div>
$("target").load("page.php");
or
$.ajax({
url: "page.php",
success: function (response) {
$("target").append(response);
});
On the plus side this separates the content which reduces initial page loading time and the content can be built server side right before it is required, on the downside my server shows a delay of ~0.1s (on average, reproducable) for AJAX calls to return (with practically no data sent back and forth). Although this might seem insignificant in the end all small delays add up and can impact user experience.
Clone templates
<template>
<div>
<img><p></p><button></button>
</div>
</template>
const template = document.querySelector("template");
var tgt = document.getElementById("target");
node = document.importNode(template.content, true);
tgt.appendChild(node);
On the plus side this option is about 10-20x faster than the 1st option (build via jQuery), but that will only become noticable after ~1000 blocks which far exceeds my use case. On the down side this 'pollutes' the page HTML code and processing of the content into the object is required through JS anyways.
Which other viable options are out there? And what is the best practice for this use case?
Solution
Since you're not using SPA approach (an example explaining that: with angular). The best (cleanest/fastest) option (in my opinion) is to fully render the blocks from the server side (you're using PHP apparently). Meaning that you'll have a file defining a single block structure of an appointment 'appointment.php' which holds the template + rendering logic, this 'appointment.php' result (after rendering) then you'll be calling (loop) in the page you need it in, as many times as you wish and with the parameters you wish, for each instance of the appointments list you have
Answered By - wiwi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.