0

I am loading my JavaScript files dynamically in the page:

<html>

<head>
    <script type="text/javascript">
        window.onload = function () {
            var script1 = document.createElement('script'),
                script2 = document.createElement('script'),
                script3 = document.createElement('script');

            script1.type = 'text/javascript';
            script1.src  = 'myScript1.js';
            script2.type = 'text/javascript';
            script2.src  = 'myScript2.js';
            script3.type = 'text/javascript';
            script3.src  = 'myScript3.js';

            document.body.appendChild(script1);
            document.body.appendChild(script2);
            document.body.appendChild(script3);
        }
    </script>
</head>

<body>

</body>
</html>

I need to know when these Scripts loaded completely. Is there any workaround or code snippets to do this?

Vahid
  • 3,384
  • 2
  • 35
  • 69
  • Possible duplicate of http://stackoverflow.com/questions/3768768/loading-javascript-dynamically-and-how-to-check-if-the-script-exists – Magicprog.fr Jul 11 '15 at 09:41
  • @Magicprog.fr, No, it's not duplicate. The question you've mensioned is asking for JavaScript existence but loaded complete. – Vahid Jul 11 '15 at 10:02

2 Answers2

1

before document.body.appendChild

scrimpt1.addEventListener('load', function() { console.log('loaded'); });

obviously you'll want to do "something useful" instead of the simple console.log I've shown

BUT ... this isn't always realiable

try this

var numScripts;
function scriptLoaded() {
    numScripts --;
    if(numScripts == 0) {
        console.log('huzzah all scripts loaded');
    }
}

then, your code

    window.onload = function () {
        var script1 = document.createElement('script'),
            script2 = document.createElement('script'),
            script3 = document.createElement('script');
        numScripts = 3;
        script1.type = 'text/javascript';
        script1.src  = 'myScript1.js';
        script2.type = 'text/javascript';
        script2.src  = 'myScript2.js';
        script3.type = 'text/javascript';
        script3.src  = 'myScript3.js';

        document.body.appendChild(script1);
        document.body.appendChild(script2);
        document.body.appendChild(script3);
    }

at the end of each of your scripts, put something like

if(windows.scriptLoaded) {
    scriptLoaded();
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Thank you for the answer. The second solution is better I think and for the first one I prefer this one: http://stackoverflow.com/a/3768844/3682369 – Vahid Jul 11 '15 at 10:04
0

Use a callback

function greetFinished() {
  alert("Do stuff finished");
}

​function greet (greeting, callback) {
  alert(greeting)
  callback (options);
}

greet("Hello",greetFinished);

greetFinished will be called inside the greet function greetFinished is a callback it will be called after the alert.

Abdullahi
  • 134
  • 8