<script> tag. But, do you know that you can put custom attributes and access it inside your script?
For example, let's take a look at this giscuss.app script tag:
<script src="https://giscus.app/client.js" data-repo="[ENTER REPO HERE]" data-repo-id="[ENTER REPO ID HERE]" data-category="[ENTER CATEGORY NAME HERE]" data-category-id="[ENTER CATEGORY ID HERE]" data-mapping="pathname" data-strict="0" data-reactions-enabled="1" data-emit-metadata="0" data-input-position="bottom" data-theme="preferred_color_scheme" data-lang="en" crossorigin="anonymous" async> </script>
Line 2 until 12 (data-repo until data-lang) are called dataset. It's a custom attributes that you can put to HTML elements. As long as you use
data- as a prefix, it's considered as dataset. You can also put your custom elements/attributes without
data- prefixed, but it's just an attribute, not dataset. Now, how do you fetch the attributes value?
Let's say you have
index.js script that you import to your code like below:
<script src="./index.js" data-attr1="val1" data-attr2="val2" attr3="val3" attr4="val4"> </script>
attr4 you can do this inside
// fetch current script tag that import this script const script = document.currentScript const dataset = script.dataset const attr1 = dataset.attr1 const attr2 = dataset.attr2 const attributes = script.attributes const attr3 = attributes.getNamedItem('attr3').value const attr4 = attributes.getNamedItem('attr4').value
As for the dataset, the
data- prefix will be removed. But for the rests, it is considered as common attributes just like
Now you can get your user input from attributes, just think of it like function arguments. It's simple and straightforward. Although you can choose between 2 methods above, I recommend you to use the
dataset since it is more semantic than just a plain attribute.
Thank you for reading!
Top comments (0)