Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- Load Javascript for only a few


Fotiman - 2:35 pm on May 17, 2012 (gmt 0)



Does not work, but isn't loading example.js for everyone:

<script type="text/javascript">
...
function called_only_a_few_times(){
var eg=document.createElement("script");
eg.type="text/javascript";
eg.src="http://www.example.com/example.js";
document.getElementsByTagName("head").item(0).appendChild(eg);
var func1Val = func1();}
...
</script>

That will load example.js asynchronously, which means it may or may not (probably not) be finished loading when you try and call func1() in the line following it. What you need is a callback when it has finished loading.

If you use jQuery, you could do something like this:


function called_only_a_few_times(){
var func1Val;
$.ajax({
url: 'http://www.example.com/example.js',
dataType: 'script',
cache: true,
success: function() {
func1Val = func1();
}
}
}
.

Alternatively

function called_only_a_few_times(){
var func1Val;
var eg = document.createElement("script");
eg.src = 'http://www.example.com/example.js';
// the type attribute is not needed/does not do anything
eg.onload = eg.onreadystatechange = function() {
var rs = this.readyState;
if (rs && rs != 'complete' && rs != 'loaded') return;
func1Val = func1();
};
// Instead of inserting in the head, insert before the first script tag
// since head could be omitted, but since we are in a script, we know
// there is at least 1 script element defined somewhere
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(eg, s);
}


Thread source:: http://www.webmasterworld.com/javascript/4454521.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com