3

I have this function which is imported directly in the HTML

function include(filename){
    var head = document.getElementsByTagName('head')[0];

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/Javascript';

    head.appendChild(script);
} 

And I want to use it to import my other JSs programatically like this

function testRunner(){
    include('Point.js');
    include('Grid.js'); 
    gridTest();
}

the JSs are showing in the HTML in the head and they look ok...

But the other JSs cannot see it.

Why ?

0

5 Answers 5

7

The included scripts are loaded asynchronously, so the include() function returns before the script file has been fully loaded.

You need to pass a callback for the onload event of the script:

function include(filename, cb){
    var head = document.getElementsByTagName('head')[0];

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/Javascript';
    script.onload = cb;

    head.appendChild(script);
} 

And then load it like this:

function testRunner() {
    include('Point.js', function() {
        include('Grid.js', function() {
            gridTest();
        });
    });
}

Of course using an existing script for dynamic loading of JavaScript would be much more comfortable, you could then probably do something like this:

require(['Point.js', 'Grid.js'], function() {
    gridTest();
});

Have a look at RequireJS: http://requirejs.org/

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

1 Comment

Thanks great example and answer !
1

That's because other JS-es are already loaded when you load your script. You need to use callback function.

1 Comment

you can use Modernizr for that
0

You must try this.

window.onload = function(){ 
var s = document.createElement('script'); 
s.src = 'YourScript.js'; 
document.getElementsByTagName('body')[0].appendChild(s); 
}

Comments

-1

You need to be sure that the files have loaded before you try to use them. Try something like:

function include(filename){
    ...
    return true;
}

if (include("grid.js")){
    testgrid();
}

1 Comment

And how exactly would he determine that synchronously? ;)
-1

To bring js files, i think you need to fetch it as objects to cache and use.

function preFetchResources(url) {
                var o = document.createElement('object');
                o.data = url;
                o.width = 0;
                o.height = 0;
                document.body.appendChild(o);
            }

This will prefetch a js file from its url and add in cache. You can access the library from there.

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.