Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script tag with both external source and body

I just came across this sample code, which has a script tag with both an external source and a body. I assume that this is a clever way to pass some information to the included script. How does it work?

<html>
  <head>
    <script src="http://unhosted.org/remoteStorage.js">{
      onChange: function(key, oldValue, newValue) {
        if(key=='text') {
          document.getElementById('textfield').value= newValue;
        }
      },
      category: 'documents'
    }</script>
  </head>
like image 959
Thilo Avatar asked Feb 03 '23 10:02

Thilo


2 Answers

The script contained in the tags will not be evaluated under normal circumstances. What I think is happening in your example is that remoteStorage.js is reading the contents itself as it is evaluated. something like this

//grab the last script tag in the DOM
//this will always be the one that is currently evaluating during load
var tags = document.getElementsByTagName('script');
var tag = tags[tags.length -1];
//force evaluation of the contents
eval( tag.innerHTML );

Although this looks neat in the markup, I, myself would just use a separate script tag and avoid this forced evaluation.

like image 90
meouw Avatar answered Feb 04 '23 22:02

meouw


Although browsers are said to ignore the contents of a script element when it has a src attribute, this just means that they don’t process it the normal way (parse and run as JavaScript code). The contents are still stored in the DOM and can be read by a script. The contents could be just about anything then, not necessarily JavaScript code but any data.

like image 40
Jukka K. Korpela Avatar answered Feb 04 '23 22:02

Jukka K. Korpela