ajax - Dynamically Included Javascript and Dependencies -
so, sort of exercise myself, i'm writing little async script loader utility (think require.js, head.js, yepnope.js), , have run across little bit of conundrum. first, basic syntax this:
using("models/somemodel", function() { //callback when dependencies loaded });
now, want know, when call made, file i'm in. ajax call, can mark flag after content loads, before eval mark using calls going specific file, unset flag after eval (i know eval evil, in case it's javascript in first place, not json, it's not evil). i'm pretty sure need, prefer script tag few reasons:
- it's semantically more correct
- easier find scripts debugging (unique file names easier through anonymous script blocks , debugger statements)
- cross-domain requests. know try use xdomainrequest, servers aren't going set that, , want ability reference external scripts on cdn's.
i tried got me needed. keep list of every time using called. when 1 of scripts loads, take of using references , incorporate them correct object file loaded, , clear global list. seems work alright in firefox , chrome, fails in ie because load events seem go off @ weird times (a jquery reference swallowed reference type , ended showing dependency). thought latch on "interactive" readystate, doesn't appear ever happen.
so come asking if here has thoughts on this. if y'all want, can post code, it's still messy , hard read.
edit: additional usages
//aliasing , multiple dependencies using.alias("ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", "jquery"); using(["jquery", "models/somemodel"], function() { //should run after both jquery , somemodel have been loaded , run }); //css , conditionals (using non-existant variables here) using.css({ src: "iefix", conditionally: browser === "msie" && version < 9 }); //should include iefix.css file if browser ie8 or below
and expound more on response below, consider file (and consider jquery alias before there still):
using(["jquery", "b"], function() { console.log("this should last (after both jquery , b have loaded)"); console.log(typeof($)); });
then b:
using("c", function() { console.log("this should second"); });
and finally, c:
console.log("this should first");
the output should be:
this should first should second should last (after both jquery , b have loaded) [object object]
commendable taking on such educational project.
however, won't able pull off quite way want it.
the news is:
- no need know file in
- no need mess eval.
you have need right there: function reference.
callback
, if will.
a rough p-code using
function be:
function using(modules, callback) { var loadedmodules = [] // ajax call load things, several different ways it.. loadedmodules[0] = loadmodule(modules[0]); loadedmodules[1] = loadmodule(modules[1]); // great, have modules // null = value `this` callback.apply(null, loadedmodules); }
Comments
Post a Comment