0

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;
}
4
  • could you tried to enclose your script at the end of your html document? Commented 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 much Commented 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) Commented 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 though Commented Dec 16, 2012 at 14:48

1 Answer 1

3

Use window.onload or jquery $(document).ready and then call this function inside ? Or call the function at the bottom of the page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.