This is my code so far, and the main problem is that the scripts are sometimes loaded after the main page is loaded, a page is requested with AJAX and uses parseScript on the output, is there a way to make this function pause and not return anything until all the scripts are loaded by the browser?
function addScriptTag(src) {
var node = document.getElementsByTagName("head")[0] || document.body;
if(node){
var script = document.createElement("script");
script.type="text/javascript";
script.src=src
node.appendChild(script);
} else {
document.write("<script src='"+src+"' type='text/javascript'></script>");
}
}
function parseScript(_source) {
var source = _source;
var scripts = source.match(/<script[^>]*src=[^>]*>/g);
if (scripts) {
for (var i = 0; i < scripts.length; i++) {
src = scripts[i].match(/src=("([^"]*)"|'([^']*)')/);
src = src[2] || src[3];
if (src) {
addScriptTag(src);
}
}
}
var scripts = new Array();
return source;
}
asked Dec 16, 2012 at 13:20
user1841964
1111 gold badge2 silver badges8 bronze badges
-
could you tried to enclose your script at the end of your html document?SaidbakR– SaidbakR2012年12月16日 13:24:11 +00:00Commented Dec 16, 2012 at 13:24
-
This isn't an option, the only option currently is adding a callback which I am not familiar with in Javascript, I have got a script in my header that loads pages dynamically with AJAX using custom URLs for bookmarking, there is just 1 page loaded at a time and I use myDiv=parseScript(AJAXFetchedCode) pretty muchuser1841964– user18419642012年12月16日 13:29:24 +00:00Commented Dec 16, 2012 at 13:29
-
@user1841964: What are you not familiar about callbacks? They should be quite simple for your situation (they are only really hard to use if your code gets too big)hugomg– hugomg2012年12月16日 13:44:42 +00:00Commented Dec 16, 2012 at 13:44
-
@missingno I would like to have the callback when the scripts get actually loaded and not just the tags added thoughuser1841964– user18419642012年12月16日 14:48:48 +00:00Commented Dec 16, 2012 at 14:48
1 Answer 1
Use window.onload or jquery $(document).ready and then call this function inside ? Or call the function at the bottom of the page.
answered Dec 16, 2012 at 13:23
Sh1d0w
9,5203 gold badges27 silver badges35 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default