Script with external source and body

I just stumbled upon this sample code that has a script tag with both an external source and a body. I assume this is a smart way to pass some information to an included script. How it works?

<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> 
+7
source share
3 answers

The script contained in the tags will not be evaluated under normal circumstances. I think in your example it is that remoteStorage.js reads the content when it is being evaluated. something like that

 //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 just use a separate script tag and avoid this forced evaluation.

+6
source

Browsers are said to ignore the contents of the script element when it has the src attribute, which means that they do not process it in the usual way (parsed and executed as JavaScript code). Content is stored in the DOM and can be read by a script. Content can be just about any, not necessarily JavaScript, but any data.

+3
source

This should not work. html specs claim that if the src attribute is in the script tag, the contents of <script></script> should be ignored and only code in src needs to be executed.

On the other hand, it will gracefully degrade in browsers that understand javascript but are not new enough to support external JS code. If there are such browsers that know, but, generally speaking, the exchange code in your fragment should NOT be executed by any decent modern browser.

+2
source

All Articles