Modred
Modred

Reputation: 269

Delay function call when dynamically loading javascript files

I am using enquire to dynamically load javascript files but hitting what I can only assume to be a loading priority problem since it works some of the time. Is there a way to hold off running a function until all files are loaded?

The relevent bit of enquire is

enquire.register("screen and (min-width: 564px)", {
    match : function() {
    loadJS('script/jquery.js');
    loadJS('script/jquery.slides.min.js');
    loadJS('script/TMSScript.js');
    }

and the load function is

function loadJS(url)
{
    var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}

The function I need to run is located at the end of TMSScript.js and it calls the jquery plugin so all 3 files need to be loaded in order for it to work. If I load all files in the header then the function will execute fine with a simple onload call in the body.

The idea is that a different method will be used on mobiles for my gallery (probably jquery mobile) and I don't want to load any unnecessary files.

Upvotes: 0

Views: 171

Answers (1)

joeellis
joeellis

Reputation: 2785

Someone may correct me, but I believe outside of either loading these three in separate script tags placed in the correct order, or loading a single js file with these plugins concatenated in the correct order, you can't. Loading a src on a programatically created element now runs in an async fashion (in current browsers anyways I beleive), meaning you wouldn't be sure exactly when it's going to return back, and in what order.

It sounds like you want to use something like browserify or require.js which can help handle what you're trying to accomplish. I suggest checking out those projects.

Upvotes: 2

Related Questions