I'm wondering if you guys can help me to perform on-demand javascript using AJAX? If you can help me with a simple example, I would really appreciate it.
my question is: how to get a javascript code from my server and execute it?
Thanks for the help
In fact, you don't even need to use AJAX for this. Simply append a new <script>
element to your body.
Plain Old Javascript :
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/scripts/example.js';
document.body.appendChild(newScript);
Here's the same code using jQuery :
// Traditional
$(document.body)
.append('<script type="text/javascript" src="/scripts/example.js" />');
// Using getScript
$.getScript('/scripts/example.js');
Here's the same code using MooTools :
// Traditional
new Element('script', {type: 'text/javascript',
src: '/scripts/example.js'}
).inject(document.body);
// Using Assets (Recommended)
new Asset.javascript('/scripts/example.js');
If you really want to use AJAX (as stated in the question) you can do so too. First, you download the javascript normally using XMLHttpRequest and when the download is finished you either eval() it or insert it inside a generated tag.
function xhr_load(url, callback) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText);
}
}
}
xhr.open("GET", url, true);
xhr.send(null);
}
// (1) download using XHR and execute using eval()
xhr_load('mylib.js', function(response) {
eval(response.responseText);
});
// (2) download using XHR and execute as an inline script
xhr_load('mylib.js', function(response) {
var script =
document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.text = response.responseText;
});
Also, Steve Souders has done amazing job in this field and I can highly recommend watching his talk on this video .
I made the following function for being able to load JavaScript files programmatically:
Usage:
loadScript('http://site.com/js/libraryXX.js', function () {
alert('libraryXX loaded!');
});
Implementation:
function loadScript(url, callback) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script"),
done = false;
script.src = url;
// Attach event handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
callback(); // execute callback function
// Prevent memory leaks in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
I use a callback function argument, that will be executed when the script is loaded properly.
Also notice that the script
element is removed from the head
after it is loaded and I remove the load
and readystatechange
events by setting them to null
, that is made to prevent memory leaks on IE.
Check an example usage here .
I use this code to load-on-demand (using jQuery). Its blocking (but i need it) you can make it synchronous using async:true
(function(script) {
var included_files = new Array();
this.include = function(script) {
var js_base = '/js/';
if (_.indexOf(included_files, script) == -1){
included_files.push(script);
$.ajax({
url: js_base+script.split('.').join('/')+'.js',
type: 'get',
dataType: 'script',
async: false,
global:false,
});
}
};
})();
It uses jQuery and Underscore.js for .indexOf
but you can ommit latter with your own indexOf function.
Good luck.
Get the JavaScript code from the server enclosed in tags, append it into DOM and execute a function. The function name to execute could come with the same request or it can be predefined.
What do need this for? Perhaps if you could elaborate your goals, a more straightforward method could be found.
Javascript gets from the web server to the user's browser in a couple of ways:
<script>
tag <script>
tags can call the code in this separate .js file CMS has shown a solid (looking, haven't tested) library independent method. Here's how you do it in Dojo.
dojo.require("namespace.object");
You may need to specifiy the path to your namespace (ie: root folder)
dojo.registerModulePath("namespace", "../some/folder/path");
See the doc for more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.