What do random colons mean in JavaScript

As with the LinkedIn api example:

<script type="text/javascript" src="https://platform.linkedin.com/in.js">
  api_key: weqrw1zwufdsiot9434re
  onLoad: onLinkedInLoad
  authorize: true
</script>

      

+3


source to share


2 answers


In script

an attribute src

tag, the content of the tag is not treated as JavaScript. The tag is allowed to have content, but this is the content of the script documentation , which is not parsed by the browser by default. It is possible that the LinkedIn API is using this text in some way (since it can retrieve it from the element), possibly as a series of pairs name:value

, but this is not JavaScript.



+9


source


In this case, there is nothing - the element script[src]

does not execute its contents. However, the script itself can use that content as a string and process it, but it wants to - while it might be more common to see JSON passed in this way, there is really no limit.

As an example of how you can use this yourself, an external script might contain:



var scripts = document.getElementsByTagName("script"),
    thisScript = scripts[scripts.length-1];
// The above works because, at the time of execution,
// the current script is the last one on the page
// (unless "defer" is used, but just don't use it :p)

var text = thisScript.textContent || thisScript.innerText,
    lines = text.split("\n"),
    map = {}, kv, l = lines.length, i;
for( i=0; i<l; i++) {
    kv = lines[i].split(":");
    if( kv.length < 2) continue; // probably a blank line
    map[kv.shift().replace(/^\s+|\s+$/g,'')] = kv.join(":").replace(/^\s+|\s+$/g,'');
    // the "shift / join" shenanigans allows for colons in values without breaking
}
// you can now use map.api_key etc.

      

+2


source







All Articles