Hey everyone, I’m trying to figure out how to send info to a JavaScript file that’s not on my site. I saw this cool thing with Yahoo Pipes where they put some data right in the script tag. It looks like this:
<script src="example.com/script.js">{"someKey":"someValue","otherKey":"otherValue"}</script>
I want to do something like that with my own scripts. How can I grab that data in my JavaScript file? Is there a special way to read it or does it just show up somewhere? I’m pretty new to this stuff, so any help would be awesome. Thanks!
PS: I tried looking it up, but I’m not sure what to search for. If anyone knows the right terms for this, that’d be super helpful too!
hey, i’ve seen something similar before. you could try using a global variable before loading ur script. like this:
then in ur external js, just use myStuff.key to get the value. its pretty simple and works well!
While the Yahoo Pipes approach is interesting, it’s not a standard method for passing data to external scripts. A more reliable technique is to use a global variable or object. Here’s what I’ve found works well:
In your HTML file, before loading the external script, declare a global variable:
<script>
var myData = {"someKey":"someValue","otherKey":"otherValue"};
</script>
<script src="example.com/script.js"></script>
Then in your external JavaScript file, you can access this data directly:
console.log(myData.someKey); // Outputs: someValue
This method is widely supported and doesn’t rely on non-standard attributes. It keeps your code clean and easy to maintain. Just make sure to declare the variable before loading the external script.
I’ve actually dealt with a similar situation in one of my projects. While the Yahoo Pipes method is interesting, it’s not a standard way to pass data to external scripts. Instead, I’d recommend using data attributes in your HTML elements.
In your HTML, add data attributes to a script tag or any other element, for example: . Then, in your external JavaScript file, access these attributes by retrieving the element via its unique ID:
var script = document.getElementById(‘myScript’);
var someValue = script.getAttribute(‘data-some-key’);
var otherValue = script.getAttribute(‘data-other-key’);
This approach is more flexible and widely supported, keeping your HTML cleaner and easier to maintain. I hope this helps. Let me know if you need any clarification.