A best practice, using public functions inside zjrJS, the cross-browser OmegaJunior Javascript Library, to load and cache data from the server.
Challenges
Requirements
Benefits
Reduce both the perceived and the actual initial loading time of the main page.
Dependencies
zjrJS.Doc.lS() to load scripts
Example
In the above example you saw that the on-demand moment is body.onLoad(). Use it to load parts of your application you don't need right away. Other moments include button pushes, menu invocations, log-in requests, and the likes.
Don't use zjrJS.Doc.lS() when...
How to do this using competitive libraries
JQuery getScript()
- Your web application needs to retrieve data from your server or data storage.
- Your web application needs to speed up initial page load by deferring some data retrieval to on-demand or on-time-out.
Requirements
- Your data can be written in javascript.
- You can add a javascript method that calls back to a pre-defined function in your main script. (Or better: you control the data retrieval.)
Benefits
Reduce both the perceived and the actual initial loading time of the main page.
Dependencies
zjrJS.Doc.lS() to load scripts
Example
<script type="text/javascript" src="zjrJS.version.js" id="zjrJS"></script>
<script type="text/javascript">/* <![CDATA[ */
zjrJS.Doc.aE(window,"load",function(){
//The reader script should be instructed to call back when done loading
zjrJS.Doc.lS("myDataReader.js", "myDataReader");
});
//This is the callback function that myDataReader.js will invoke
function myDataReaderCallback(){
//Now we know the reader is loaded and ready, let's get some data.
//This data script should also call back when done loading.
zjrJS.Doc.lS("myData.js", "myData", 30);
}
function myDataCallback(){
//Now we know the data is loaded and ready, do something with the data
}
/* ]]> */</script>
In the above example you saw that the on-demand moment is body.onLoad(). Use it to load parts of your application you don't need right away. Other moments include button pushes, menu invocations, log-in requests, and the likes.
Don't use zjrJS.Doc.lS() when...
- When you do not control, or did not sign agreements on the script you invoke. See the JQuery example below.
- When you need to load a CSS or other media file that does not contain client side script.
- When for some inexplicability you are required to use AJAX.
How to do this using competitive libraries
JQuery getScript()
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">/* <![CDATA[ */
//The reader script does not need to be instructed to call back when done loading
//because we provide the callback function right here.
$.getScript("myDataReader.js", function(){
//Now we know the reader is loaded and ready, let's get some data.
$.getScript("myData.js", function(){
//Now we know the data is loaded and ready, do something with the data.
//Just mind your closures.
});
});
/* ]]> */</script>