Reputation: 5856
I would like to include the same javascript file more than once on a page. This is because different variables are defined using the "data" attr to get different data.
Here is an example of what i mean:
<script id="sc_widget" data-key="rsl2xlfiovx09mkwofom" data-id="jwks97n15dpqge35jfmm" src="http://example.co.uk/sc.js" type="text/javascript"></script>
<script id="sc_widget" data-key="rsl2xlfiovx09mkwofom" data-id="fw8zy246n8vhf5f8du7n" src="http://example.co.uk/sc.js" type="text/javascript"></script>
The above obviously detects and displays the information from the script twice, but the information displayed is the same for both, when it should be different.
My js file:
var key = document.getElementById("sc_widget").getAttribute("data-key");
var id = document.getElementById("sc_widget").getAttribute("data-id");
$.ajax({
type: "post",
url: "//example.co.uk/sc.php?key="+ key + "&id="+ id,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
$('.sc_ouput').html(responseData);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
So is there anyway to accomplish this?
Upvotes: 0
Views: 453
Reputation: 944320
id
attributes must be unique in an HTML document.
document.getElementById("sc_widget")
will always get the first element with the matching ID. The others will be ignored as the browser attempts to recover from the error.
Instead, get the last <script>
element in the document.
var scripts = document.querySelectorAll("script");
var script = scripts[scripts.length - 1];
var key = script.dataset.key;
var id = script.dataset.id;
You'll also need to change this logic:
$('.sc_ouput').html(responseData);
… since it replaces the content of the first element that is a member of that class.
Possibly you'll want to use some logic such as replacing the previous sibling of the script
element you've already found.
Note that since you are using an asynchronous function inside the script, you'll need to wrap it in an IIFE to close over the script
variable so it doesn't get overwritten by the next script before the Ajax has finished.
Upvotes: 2
Reputation: 29521
I would like to include the same javascript file more than once on a page.
You don't need to include and re-include the same file.
You simply need to write a function which takes one or more parameters:
function myFunction(fruit) {
/* [... CODE HERE ...] */
}
if you want to run the script once on the data apple
and once on the data banana
, you can then do the following:
myFunction(apple);
myFunction(banana);
Upvotes: 1