Experimenting with injecting CSS, javascript files and evaluating JSON objects

There is much discussion here www.phpied.com/javascript-include on how to dynamically include javascript and css files. I've modified some of the code examples given there - mainly to allow you to decide whether or not to allow a script to be injected more than once, depending on whether the script is assigned an id attribute.

This allows for the fact that both single and multiple injection of scripts can be appropriate. It also overcomes the problem you get by comparing the src attribute: if you add the random number to the end of the URL with "'?rand='+Math.random()" then the src attribute will different each time, so duplicated scripts won't be detected.

Evaluation of JSON objects by script injection

Yahoo document an interesting variation here: developer.yahoo.com/common/json.html

Yahoo provides an API that returns search results as an object encoded in JSON. As a variant you can append "&callback=ws_results" to the URL and they will return to you the JSON string enclosed by your callback function name and parentheses: "ws_results(json_string)". ws_results is the name of a javascript function already present in your code. Then by placing src=URL inside the script tags results in your ws_results function running with the JSON object as its parameter.

They have a working example at the above URL. I've modified the code and it is running here. Look at the source to understand what is going on.

Click on list items below to see theses ideas at work. Messages will be added at the bottom of the page:

Messages will go here: