March 4, 2001 - Advance Loading of External Scripts
March 4, 2001 Advance Loading of External Scripts Tips: March 2001
Yehuda Shiran, Ph.D.
|
<SCRIPT LANGUAGE="JavaScript" SRC="browserSniffer.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" SRC="docjslibSuperClass.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" SRC="createTheProperSubClass.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
var classSelectionObj = new createTheProperSubClass();
var myBrowserAPIObj = classSelectionObj.getTheProperSubClass();
// -->
</SCRIPT>
The browser-specific objects are loaded on the fly in createTheProperSubClass.js
:
var browserType = new browserSniffer();
if (browserType.ie4) {document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibIE4SubClass.js"><\/SCRIPT>');}
else if (browserType.ie5) {document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibIE5SubClass.js"><\/SCRIPT>');}
else if (browserType.ns4) {document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibNS4SubClass.js"><\/SCRIPT>');}
else if (browserType.ns6) {document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibNS6SubClass.js"><\/SCRIPT>');}
But originally, we wanted to load these browser-specific objects inside the function createTheProperSubClass()
in the following way:
function createTheProperSubClass() {
var browserType = new browserSniffer();
if (browserType.ie4) {
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibIE4SubClass.js"><\/SCRIPT>');
this.className = "docjslibIE4SubClass";
}
else if (browserType.ie5) {
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibIE5SubClass.js"><\/SCRIPT>');
this.className = "docjslibIE5SubClass";
}
else if (browserType.ns4) {
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibNS4SubClass.js"><\/SCRIPT>');
this.className = "docjslibNS4SubClass";
}
else if (browserType.ns6) {
document.write('<SCRIPT LANGUAGE="JavaScript" SRC="docjslibNS6SubClass.js"><\/SCRIPT>');
this.className = "docjslibNS6SubClass";
}
this.getTheProperSubClass = getTheProperSubClassMethod;
function getTheProperSubClassMethod() {
// example: return new docjslibIE5SubClass();
return eval('new ' + this.className + '()');
}
}
We found out that this code does not load the objects and the browser complains. One of the reasons may be that when the loading is done within the function above, it is actually done too close to its first usage. JavaScript does not wait for external scripts to load -- it continues on with the main script. When loading the objects the way we did succeed, the browser-dependent object is being loaded way in advance of its first usage.