I don't know how I can synchronize next code:
javascript: (function() {
var s2 = document.createElement('script');
s2.src = 'http://192.168.0.100/jquery.js';
document.body.appendChild(s2);
s = document.createElement('link');
s.rel = "stylesheet";
s.href = "http://192.168.0.100/1.css";
s.type = "text/css";
document.body.appendChild(s);
})();
//var startTime = new Date().getTime();
//while (new Date().getTime() < startTime + 1000);
$(document).ready(function(){
b="c:\1円.txt";
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile(b, true);
f1.WriteLine("Testing") ;
document.writeln("File " + b + " is created.");
});
When I run this script at first I get an error SCRIPT5009: '$' is undefined. I think that is because jQuery library is yet no loaded. When I try to run the same script after error's appearencing - it behavior is corect. For synchonization I try to use code that is commented in upper listing. Is works (not always). But I understand that is no strict synchronization (it dependet of concrete situation). How can I use more clever synchronization?
3 Answers 3
(function($){
//use $ now
$(function(){
//dom ready
});
})(jQuery);
Be sure to load this libary in the footer below the jquery library.
Comments
This is due to the fact that putting in the script tag via appendChild dhtml method makes it evaluate async. To listen for it getting 'ready' as youre doing it on the document - follow this pattern
(function() {
var s2 = document.createElement('script');
s2.src = 'http://192.168.0.100/jquery.js';
document.body.appendChild(s2);
s2.onload = s2.onreadystatechange = function(){
if(s2.readyState == "complete") $(document).ready(function(){
b="c:\1円.txt";
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile(b, true);
f1.WriteLine("Testing") ;
document.writeln("File " + b + " is created.");
});
}
s = document.createElement('link');
s.rel = "stylesheet";
s.href = "http://192.168.0.100/1.css";
s.type = "text/css";
document.body.appendChild(s);
})();
3 Comments
onreadystatechange fires on scripts only when the loading has completed? In XMLHttpRequest objects, it fires several times going through readyStates until it finally gets to 4 when it's done.The issue is that the line with the $ is being hit when the script tag has been added but before the file has been downloaded. Normally browsers block while loading JavaScript which prevents this issue, but since you're doing it programatically you don't get the standard synchrony.
Your best bet would be to wait for the script to be loaded. There's information here:
Dynamic, cross-browser script loading
On catching the load event for the completion of the script download. You can then call your existing $ ready function as a callback to that event. I'd suggest using a loader that is made for this stuff, or just use a standard script tag in the DOM unless you have a compelling reason not to.