I want to keep the code short and clean. So I'm importing tons of HTML files.
I have this in head:
<script>
var loadHtml(file) {
$("#LoadHTML").load("html/file.html");
});
</script>
And this in body:
<div id="LoadHTML"></div>
The problem is I have to duplicate the script for each <div> I have.
Is there a way I can make a placeholder in the script and do what I have visualized?
<!-- Head -->
<script>
$(function(){
$("#LoadHTML").load("html/{data}.html");
});
</script>
<!-- Body -->
<div id="LoadHTML" data="file"></div>
How do I do it so I only have to use the script once?
-
1Just keep in mind making lots of request vs 1 request with long code can make your page load a lot slower - browsers have a max number of request they can process so they have to wait for each one to complete before moving onto the next when the max number is reachedPete– Pete2017年11月20日 16:27:49 +00:00Commented Nov 20, 2017 at 16:27
-
This isn't a good way to go about simplifying your page. You'd be better off using a client-side rendering framework (like React or Angular).JLRishe– JLRishe2017年11月20日 16:29:22 +00:00Commented Nov 20, 2017 at 16:29
3 Answers 3
You could group the elements to be loaded by a common class and use a data attribute to set the URL to target the AJAX request to, something like this:
$(".load").each(function() {
$(this).load($(this).data('target'));
});
<div class="load" data-target="html/file.html"></div>
<div class="load" data-target="html/foo.html"></div>
<div class="load" data-target="html/bar.html"></div>
With that being said, I would strongly suggest you use server side includes where possible instead of your current approach. Using client side requests as you are will make many more, potentially needless, requests to your server, and hence slowing it down.
5 Comments
$(".load").each(function() { $(this).load("html/" + $(this).data('target') + ".html"); }); and just have the data as the name?Yes you can!
$("#LoadHTML").load("html/" + data + ".html");
where data is keyword of your template.
Comments
id has to be unique. You may have to generate the id name so it would be #LoadHTML1, #LoadHTML2, #LoadHTML3, etc.
Alternatively use class so it's ".LoadHTML"