0

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?

9
  • 2
    Can you add the code showing how the script is reading the data-* attributes? Commented Mar 21, 2018 at 14:47
  • 2
    Although you can, it is bad practice to use a single id on multiple elements. Commented Mar 21, 2018 at 14:49
  • @phuzi this will get changes to a class Commented Mar 21, 2018 at 14:51
  • @JamesThorpe i ahve added my js. Commented Mar 21, 2018 at 14:52
  • @phuzi — "Although you can, it is bad practice to use a single id on multiple elements" — No. It is forbidden to reuse ids. Commented Mar 21, 2018 at 14:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

The question clearly states that both scripts should be taken in account. Getting the last one instead won't help. Additionally, querying by 'script' is error prone and misses the chance to resolve one of the main errors the question.
@Barthy — Getting the last one will help because the last one will be the script that has just loaded. So when the first script loads, it will be the last one. Later, the second script will load and then the second one will be the last one. This only gets error prone if you do things like defer, which these scripts are not.
Alright, I did not know that. To improve the quality of your answer, you should write that down, too. I removed my downvote.
May be worth noting that document.currentScript is now fairly widely supported too - I think this would also then work for async and defer scripts.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.