Reputation: 23
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?
Upvotes: 2
Views: 3016
Reputation: 19
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"
Upvotes: -1
Reputation: 337560
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.
Upvotes: 4
Reputation: 2406
Yes you can!
$("#LoadHTML").load("html/" + data + ".html");
where data is keyword of your template.
Upvotes: 0