Load javascript sequentially from javascript code - javascript

I have a javascript widget that is included in a page by inserting a single script tag (as the application should be easiliy distributable):
<script type="text/javascript" src="loadMyWidget.js"></script>
loadMyWidget.js then needs to load multiple script files, which has to run in a certain sequence. I've tried to load them async by inserting script elements into the DOM, but that doesn't give me control of the sequence.
I also tried using head.js which is great for modern browsers, but I can't get it to work in IE7 and 8.
Minifying the scripts into one file is unfortunately difficult, as it is composed of a number of files from different projects and I wouldn't know when to update the script.
As simple as it seems, I need to load javascript files from javascript code in a certain sequence and get it to work in all browsers, including IE7 and 8.

If you need vanilla JS, something like this could work:
function loadScripts(scripts, complete) {
var loadScript = function( src ) {
var xmlhttp, next;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return;
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText);
next = scripts.shift();
if ( next ) {
loadScript(next);
} else if ( typeof complete == 'function' ) {
complete();
}
}
}
xmlhttp.open("GET", src , true);
xmlhttp.send();
};
loadScript( scripts.shift() );
}
loadScripts(['jquery.js','jquery.plugin.js'], function() {
console.log('loaded');
});
Tested in Chrome, should work in IE too.

If you're using jQuery.getScript() you can use it as a $.when() to hold off execution until things have stopped loading.
If by "sequential execution" you mean that you need to load the requisites before execution the following will work
$(function(){
$.when(
$.getScript("/script1"),
$.getScript("/scirpt2"),
$.getScript("/script3")
}).done(function(){
// do stuff with the contents of my new script files
});
If by sequential execution you mean that you need to execute files one after the other try this:
$.Deferred()
.then(function () { return $.getScript("/script1"); })
.then(function () { return $.getScript("/scirpt2"); })
.then(function () { return $.getScript("/script3"); })
.resolve();
Of course, this requires jQuery, which after your edits, this may not work for you.
Suggested Reading
http://api.jquery.com/jQuery.getScript
http://api.jquery.com/category/deferred-object/
http://api.jquery.com/jQuery.when/

I have run into this exact same issue and handled it with:
document.write('<script type="text/javascript" src="other1.js"></script>');
document.write('<script type="text/javascript" src="other2.js"></script>');
runSomeCode();
The code will be loaded and run synchronously. Pros: simple, light, cross browser compliant, no deps. Cons: ugly.
More details: https://stackoverflow.com/a/3292763/235179

Have you tried require.js? http://requirejs.org/

function loadScript(arrayOfUrlStrings, callback) {
var numScripts = arrayOfUrlStrings.length;
var count = 0;
var headElement = document.getElementsByTagName('head')[0]
function onLoad() {
count += 1;
if (count === numScripts) {
callback();
} else {
addScript();
}
}
function addScript() {
var script = document.createElement('script');
script.src = arrayOfUrlStrings[count];
script.onload = onLoad;
headElement.appendChild(script);
}
addScript();
}

Related

script.readyState is undefined in IE11 & FF

I just worked on a dynamic script loader which works fine in IE9 but not in IE11 and not in FF.
Here is my code:
function getResourceScript(filename)
{
var script = document.createElement('script');
script.setAttribute('src', mShuttlePath + "scripts/" + filename);
script.setAttribute('type', 'text/javascript');
script.setAttribute('language', 'javascript');
document.getElementsByTagName('head')[0].appendChild(script);
}
function documentLoadInit()
{
if (document.readyState == 'complete')
{
// check if all scripts are loaded
for (var n = 0; n < document.scripts.length; n++)
{
if (document.scripts[n].readyState != "complete" && document.scripts[n].readyState != "loaded")
{
setTimeout(documentLoadInit, 49);
return false;
}
}
Init();
}
else
{
setTimeout(documentLoadInit, 49);
}
}
getResourceScript("core/core.js");
getResourceScript("core/ajax.js");
The main problem here is, that the script.readyState is dropped in IE11 - so much I found out!
But how to replace it? How to check When the script is loaded / is finished?
Any ideas?
From the MSDN:
Note: For the script element, readyState is no longer supported. Starting with Internet Explorer 11, use onload. For info, see Compatibility changes.
So, instead of checking for the readyState you can use something like this:
if (!script.addEventListener) {
//Old IE
script.attachEvent("onload", function(){
// script has loaded in IE 7 and 8 as well.
callBack();
});
}
else
{
script.addEventListener("load", function() {
// Script has loaded.
callBack();
});
}
Also, I'm pretty sure that you can improve your code. And setInterval() is more suitable in this case. Read a little bit about how to use dom events and if you still have compatibility issues, here is something that you could use:
function loadExtScript(src, test, callback) {
var s = document.createElement('script');
s.src = src;
document.body.appendChild(s);
var callbackTimer = setInterval(function() {
var call = false;
try {
call = test.call();
} catch (e) {}
if (call) {
clearInterval(callbackTimer);
callback.call();
}
}, 100);
}
The function takes a test as a parameter. Since you are the designer of the app, you’ll know what successful test is. Once this test is true, it will execute the callback.
Actually I think you're asking if the document is ready before it becomes ready. You need to set up a state change listener and check each time the document state changes.
document.onreadystatechange = function () {
if (document.readyState == "complete") {
initApplication();
}
}
Read the documentation: https://developer.mozilla.org/en-US/docs/Web/API/document.readyState

How to stop further javascript calls if jquery fails to load?

I'm trying to handle JQuery not loading.
(this is for a javascript api, frequently the developer consuming it forgets to include jquery, hence I want to instruct them on what is missing)
I have a bunch of code in various files that runs on document.ready
e.g.
(function ($, undefined) {
//stuff
})( jQuery );
If JQuery is not loaded then the code above breaks.
A workaround I've found is to add a check for Jquery instead through a function
e.g.
(function ($, undefined) {
//stuff
})( JQueryCheck() );
function JQueryCheck() {
if (window.jQuery == undefined)
alert("no jquery");
else
return jQuery;
}
I'm not sure if this is strong enough, if theres a better way to do it then let me know.
On top of this I want prevent the other document.readys from running, theres no point as all depend on JQuery being loaded.
This must be common issue but I'm struggling to find a solution.
Don't load script files like this <script src="some-path"></script> in Html
instead do this:
if(window.jQuery){
$.getScript('path to js file');
}
This checks for jquery and if it exists, it loads the script and executes it.
Try this:
function JQueryCheck() {
return !!jQuery;
}
Or:
function JQueryCheck() {
try{
jQuery();
} catch(e){
if(e){
return false;
} else {
return true;
}
}
}
Or:
function JQueryCheck() {
if(window.jQuery){
return true;
}else{
return false;
}
}
Good luck!
Your code should work fine, but you could simplify it a bit:
(function ($, undefined) {
if(!$) {
return alert("no jquery");
}
//stuff
})(window.jQuery);
You could also just load it when it's not loaded already:
(function (undefined) {
if(!window.jQuery) {
var script = document.createElement("SCRIPT");
script.src = 'http://code.jquery.com/jquery-2.1.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback();
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(main);
} else {
main();
}
}());
function main() {
alert("jquery loaded");
};
Taken from https://stackoverflow.com/a/10113434/941764
Whilst it would be best to solve the issues you are having with it not loading this will do what you want it to:
if(window.jQuery) {
//jQuery Code
}
Alternatively if you're after loading a local file if a hosted one has failed, this would work:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery.min.js"><\/script>')</script>

conditionally loading external javascript libraries in my plugin

I have written a plugin that depends on external libraries that I want to include conditionally, that is, the user can choose to not have them be included automatically in case the user's web site already has those libraries. Here is some pseudocode to illustrate the issue
<script type="text/javascript" src="path/to/plugin.js"></script>
<script type="text/javascript">
PLUGIN.init({
"param1": "foo",
"parma2": 33,
"include": {"jquery": 0, "googlemaps": 0}
});
</script>
In my plugin script
var PLUGIN = {
"init": function(obj) {
if (obj.include.googlemaps !== 0) {
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
}
if (obj.include.jquery !== 0) {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
}
.. do more things ..
}
The problem is that when I am ready to "do more things," the libraries don't seem to be loaded yet. I get an error that jquery not found, or google maps not found. I can solve this by changing my code to
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
var PLUGIN = {
"init": function(obj) {
.. do more things ..
}
but now the user can't control loading the libraries or not loading them. Suggestions? Workarounds?
Update: Thanks for the suggestions, you all, but no joy so far. Here is what I am doing, and what is happening. Since I am potentially loading 0 or more scripts (the user can optionally decide which scripts need not be loaded), I have made my code like so
"importLib": function(libPath, callback) {
var newLib = document.createElement("script");
if (callback !== null) {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
},
"init": function(obj) {
var scripts = [];
if (obj.include.googlemaps !== 0) {
scripts.push("http://maps.google.com/maps/api/js?sensor=true&v=3.6");
}
if (obj.include.jquery !== 0) {
scripts.push("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js");
}
if (obj.include.anotherlib !== 0) {
scripts.push("http://path/to/another/lib.js");
}
var len_scripts = scripts.length,
callback = null;
if (len_scripts > 0) {
for (var i = 0; i < len_scripts; i++) {
// add callback only on the last lib to be loaded
if (i == len_scripts - 1) {
callback = function() { startApp(obj) };
}
importLib(scripts[i], callback);
}
}
// Start the app rightaway if no scripts need to be loaded
else {
startApp(obj);
}
},
"startApp": function(obj) {
}
What happens is that Firefox croaks with a attempt to run compile-and-go script on a cleared scope error, and Safari doesn't get that error, but doesn't load anything. Funnily, Safari error console shows no error at all. Seems like the Firefox error is caused by the line document.head.appendChild(newLib); which, if I comment, the error goes away, but of course, the web page doesn't load correctly.
You should add each script as a DOM node and use the onload attribute to take action when it has completed loading.
function importLib(libPath, callback) {
var newLib = document.createElement("script");
newLib.onload = callback;
newLib.src = libPath;
document.head.appendChild(newLib);
}
Above, the libPath argument is the URL of the library, and the callback argument is a function to call when loading is complete. You could use it as follows:
importLib("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js", function() {
alert("jquery loaded!");
nowDoSomething(aboutIt);
});
By the way: in general, document.write is not a good solution for most problems (but I won't say never the right solution -- there are exceptions to every rule).
the above solution would work in modern browsers but for IE 7/8 u might wanna added little extra code, something like this:
function importLib(libPath, callback) {
var newLib = document.createElement("script");
if (navigator.userAgent.indexOf('MSIE') !== -1) {
newLib.onreadystatechange = function () {// this piece is for IE 7 and 8
if (this.readyState == 'complete') {
callback();
}
};
} else {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
}
I encountered the same issue. One workaround if you are writing your site in .NET is by conditionally writing the script reference before the page loads from the code behind. My issue is when remote users access my app over VPN, it blocks access to the internet, thus google maps cannot be referenced. This prevents the rest of the page from loading within a reasonable timeframe. I tried controlling the script reference of the google maps library via jQuery's getScript() command, but as you found out, the subsequent google maps configuration code runs before the external library is referenced.
My solution was to conditionally reference google maps from code behind instead:
VB (code behind):
'if VPN mode is not enable, add the external google maps script reference (this speeds up the interface when using VPN significantly)
If Session("VPNMode") = False Then
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.AppendLine("")
sb.AppendLine("<script type='text/javascript'")
sb.Append(" src='http://maps.google.com/maps/api/js?v=3&sensor=false'>")
sb.Append("</script>")
Dim header As LiteralControl = New LiteralControl
header.Text = sb.ToString()
Me.Page.Header.Controls.Add(header)
End If
Client side script (javascript):
<script type='text/javascript'>
$(function () {
if ($("input[name*='VPN']").is(":checked"))
{ }
else {
loadGoogleMap()
}
});
function loadGoogleMap() {
hazsite = new google.maps.LatLng(hazLat, hazLong);
map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 18, center: hazsite, mapTypeId: google.maps.MapTypeId.SATELLITE });
var marker = new google.maps.Marker({
position: hazsite,
map: map,
title: "Site Location"
});
}
</script>

Verify External Script Is Loaded

I'm creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.
If I can verify the script is not loaded I'll load it using:
jQuery.getScript()
How can I verify the script is loaded because I don't want the same script loaded on the page more than once? Is this something that I shouldn't need to worry about due to caching of the script?
Update:
I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I'm hoping I can use the name of the script to verify it's actually loaded.
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter() functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.
Key points for me were
add an #id tag, so it's easy to find, and not duplicate
Use .onload() to wait until the script has finished loading before using it
mounted() {
// First check if the script already exists on the dom
// by searching for an id
let id = 'googleMaps'
if(document.getElementById(id) === null) {
let script = document.createElement('script')
script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
script.setAttribute('id', id)
document.body.appendChild(script)
// now wait for it to load...
script.onload = () => {
// script has loaded, you can now use it safely
alert('thank me later')
// ... do something with the newly loaded script
}
}
}
#jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:
function isScriptLoaded(src)
{
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
UPDATE July 2021:
The accepted solutions above have changed & improved much over time. The scope of my previous answer above was only to detect if the script was inserted in the document to load (and not whether the script has actually finished loading).
To detect if the script has already loaded, I use the following method (in general):
Create a common library function to dynamically load all scripts.
Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).
I use something like the following loadScript() function to load the script that uses callback functions to inform the calling modules if the script finished loading successfully.
I also use additional logic to retry when script loading fails (in case of temporary network issues).
Retry is done by removing the <script> tag from the body and adding it again.
If it still fails to load after configured number of retries, the <script> tag is removed from the body.
I have removed that logic from the following code for simplicity. It should be easy to add.
/**
* Mark/store the script as fully loaded in a global variable.
* #param src URL of the script
*/
function markScriptFullyLoaded(src) {
window.scriptLoadMap[src] = true;
}
/**
* Returns true if the script has been added to the page
* #param src URL of the script
*/
function isScriptAdded(src) {
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
/**
* Returns true if the script has been fully loaded
* #param src URL of the script
*/
function isScriptFullyLoaded(src) {
return src in window.scriptLoadMap && window.scriptLoadMap[src];
}
/**
* Load a script.
* #param src URL of the script
* #param onLoadCallback Callback function when the script is fully loaded
* #param onLoadErrorCallback Callback function when the script fails to load
* #param retryCount How many times retry laoding the script? (Not implimented here. Logic goes into js.onerror function)
*/
function loadScript(src, onLoadCallback, onLoadErrorCallback, retryCount) {
if (!src) return;
// Check if the script is already loaded
if ( isScriptAdded(src) )
{
// If script already loaded successfully, trigger the callback function
if (isScriptFullyLoaded(src)) onLoadCallback();
console.warn("Script already loaded. Skipping: ", src);
return;
}
// Loading the script...
const js = document.createElement('script');
js.setAttribute("async", "");
js.src = src;
js.onload = () => {
markScriptFullyLoaded(src)
// Optional callback on script load
if (onLoadCallback) onLoadCallback();
};
js.onerror = () => {
// Remove the script node (to be able to try again later)
const js2 = document.querySelector('script[src="' + src +'"]');
js2.parentNode.removeChild(js2);
// Optional callback on script load failure
if (onLoadErrorCallback) onLoadErrorCallback();
};
document.head.appendChild(js);
}
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion #Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
Create the script tag with a specific ID and then check if that ID exists?
Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?
Edit: following feedback that a code example would be useful:
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
if(scripts.length){
for(var scriptIndex in scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
for(var scriptIndex in document.scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :
if(!$("body").data("google-map"))
{
console.log("no js");
$.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
$("body").data("google-map",true);
},function(){
alert("error while loading script");
});
}
}
else
{
console.log("js already loaded");
}
I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again.
It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.
window.addEventListener('error', function(e) {
if (e.target.nodeName === 'SCRIPT') {
var scriptTag = document.createElement('script');
scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
document.head.appendChild(scriptTag);
}
}, true);
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
My idead is to listen the error log if there is an error on script loading.
const checkSegmentBlocked = (e) => {
if (e.target.nodeName === 'SCRIPT' && e.target.src.includes('analytics.min.js')) {
window.isSegmentBlocked = true;
e.target.removeEventListener(e.type, checkSegmentBlocked);
}
};
window.addEventListener('error', checkSegmentBlocked, true);
Some answers on this page are wrong. They check for the existence of the <script> tag - but that is not enough. That tells you that the tag was inserted into the DOM, not that the script is finished loading.
I assume from the question that there are two parts: the code that inserts the script, and the code that checks whether the script has loaded.
The code that dynamically inserts the script:
let tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'foo';
tag.src = 'https://cdn.example.com/foo.min.js';
tag.onload = () => tag.setAttribute('data-loaded', true); // magic sauce
document.body.appendChild(tag);
Some other code, that checks whether the script has loaded:
let script = document.getElementById('foo');
let isLoaded = script && script.getAttribute('data-loaded') === 'true';
console.log(isLoaded); // true
If the both of those things (inserting and checking) are in the same code block, then you could simplify the above:
tag.onload = () => console.log('loaded');
I found a quick tip before you start diving into code that might save a bit of time. Check devtools on the webpage and click on the network tab. The js scripts are shown if they are loaded as a 200 response from the server.

how to load javascript dynamically

I try to load some js files dynamically,for example:
function openInforWindow(){
//check if the InforWinow.js has been loaded or not
if(window.InforWindow){
//do the right thing
}
else {
loadJs('xxxxxx/InforWindow.js');
// do the right thing
//but here ,the infowindow is not definded yet.
}
}
function loadJs(filename){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
How to make sure that the vars or functions in the js which is dynamically loaded can be add to the javascript execute environment so I can use them ?
adding a script element isn't a blocking operation, this means that your loadJs method returns immediately when your external script isn't even loaded (nor interpreted). You have to wait for it to load.
function openInforWindow(){
//check if the InforWinow.js has been loaded or not
if(window.InforWindow){
//do the right thing
}
else {
var loadHandler = function() {
//do stuff with inforWindow
};
loadJs('xxxxxx/InforWindow.js', loadHandler);
}
}
function loadJs(filename, handler){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "js");
fileref.onreadystatechange = function () {
if (this.readyState == 'complete')handler();
};
fileref.onload = handler;
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref);
}
One approach could be to load the script using jQuery's AJAX loader. Example below:
function loadJs(filename, functionToCall){
$.getScript(filename, functionToCall);
}
Now, you just need to call loadJs("script.js", callback);, and it will first completely load script.js, and then run callback().
You can dynamically insert a <script/> tag into your document, here is a script that will work in firefox/chrome, you may need a bit of tweaking in IE:
loadJs = function(src) {
var script = document.createElement('SCRIPT');
script.setAttribute('src', src);
document.getElementsByTagName('HEAD')[0].appendChild(script);
}
Then wait for the document.onload event to fire, your window.InforWindow should be loaded at that stage.
document.addEventListener('load', function () {
// Your logic that uses window.InforWindow goes here
}, false);
Note that IE does the load event listener slightly differently:
document.attachEvent('onload', function() {
// Your logic that uses window.InforWindow goes here
});

Categories