How to Auto Include a Javascript File

2018-10-15 18:06

阅读:738

Form:
Author:MarkKahn

ManydevelopershavealargelibraryofJavaScriptcodeattheirfingertipsthattheydeveloped,theircolleguesdeveloped,orthattheyvepiecedtogetherfromscriptsallovertheInternet.Haveyoueverthoughtthatitwouldbenicetonothavetosearchthroughallthosefilesjusttofindthatonefunction?ThisarticlewillshowyouhowdynamicallyincludeanyJavaScriptfile,atruntime,bysimplycallingafunctioninthatfile!

Heresanexample:Youhaveafunctionfoo()infilebar.js.Inyourcode,youknowthatfoo()mightbecalled,butitprobablywontbebecausemostpeopledonotuseitsfunctionality.Youdontwanttoforcetheusertodownloadbar.jsunlessitsgoingtobeusedbecauseitsafairlylargefile.Hereyoulllearnhowtomakeafakefoo()functionthatactuallyloadsbar.jsontheflyandthencallstherealfoo()function.

DynamicallyLoadingaScript
Asmanydevelopersknow,thereareatleasttwodifferentwaystodynamicallyloadascriptatruntime.Thefirstistocreateascriptobjectandappendittothedocument.ThesecondistouseanXMLHTTPrequesttograbthesourcecode,andtheneval()it.

Itisthissecondmethodthatweregoingtouse,andweregoingtoexploitthefactthatanXMLHTTPrequesthasthecapabilitytocompletelystallanyscriptactivity.

First,somebasics:howtocreateanXMLHTTPObject.Thereareasmanydifferentfunctionstoreturnacross-browserXMLHTTPObjectastherearedevelopersthatworkwithAJAX.Ihappentohavemyownaswell,andheresasimplifiedexampleofthat:

复制代码 代码如下:
functiongetXMLHttpObj(){
if(typeof(XMLHttpRequest)!=undefined)
returnnewXMLHttpRequest();

varaxO=[Msxml2.XMLHTTP.6.0,Msxml2.XMLHTTP.4.0,
Msxml2.XMLHTTP.3.0,Msxml2.XMLHTTP,Microsoft.XMLHTTP],i;
for(i=0;i<axO.length;i++)
try{
returnnewActiveXObject(axO[i]);
}catch(e){}
returnnull;
}

MostbrowsersotherthanInternetExplorer5or6haveabuilt-inXMLHttpRequestobject.InternetExplorer7,whenitsreleased,willalsohavethisobjectnatively.Thefirstthingwedoischecktoseeifthisobjectexists.Ifitdoes,wecreateaninstanceofitandthatsit.Iftheobjectdoesntexist,weattempttocreateoneofseveralActiveXObjects.Wedontknowwhatobjectsourusershaveinstalled,soweattempttocreateseveraldifferentXMLHTTPobjects,startingwiththenewestones.

Nowinordertodynamicallyloadfunctions,wefirstneedtodefinethem.Wecoulddothisonefunctionatatime,butinsteadofhard-codingdozensoffunctions,wecanchoosetojustmakeanobjectorarraywithallthefilenamesandthefunctionsyouwanttohaveauto-included:

复制代码 代码如下:
varautoIncludeFunctions={
scripts/file1.js:[function1,function2,function3],
scripts/file2.js:[function4,function5,function6],
scripts/file3.js:[function7,function8,function9]
}


OurautoIncludeFunctionsobjectshouldcontainalistofJavaScriptfiles,aswellasalistoffunctionsinthosefiles.HereweareusingshorthandJavaScriptnotationtocreateboththeobjectandthearrays,butthesamethingcouldbeaccomplishedinmanydifferentways.

These.jsfilescancontainanycodeyouhaveavailable,suchasJavaScriptmenus,animations,etc.Thesimplestexamplewouldbeafiletitledfile1.jsthatonlycontainedfunctionfunction1(){alert(Hello,World!);}.

Notethatifanyofthesefilescontainfunctionswiththesamenameasanotherfile,onlythelastfunctionlistedwillbeused.

Tomakethingsabiteasier,weregoingtomakeafunctionthatwillpullaJavaScriptfiledownandexecuteit.Itsveryimportant,inourcase,thatthethirdparamatersenttotheXMLHTTPobjectbefalse.Thisforcesthescripttowaitfortheresponsetodownloadasopposedtocontinuingonwithothercode.

复制代码 代码如下:
functionloadScript(scriptpath,functions){
varoXML=getXMLHttpObj();
oXML.open(GET,scriptpath,false);
oXML.send();
eval(oXML.responseText);
for(vari=0;i<functions.length;i++)
window[functions[i]]=eval(functions[i]);
}
TheloadScriptfunctionexpectstwoarguments:scriptpathandfunctions.scriptpathshouldcontaintheURLtoyourJavaScriptfile,andfunctionsisthearrayoffunctionsthatexistinthisJavaScriptfile.

Asyoucansee,thecodetopullandexecuteascriptisstraightforward.Thebrowserfirstdownloads,andtheninterpretstheJavaScriptfile.IfyouvereadanyotherarticlesonAJAXdevelopment,youmightrememberthatinmostcasesthethirdargumentsenttotheopen()functionofanXMLHTTPobjectisusuallytrue.Inourcasewehaveitsettofalse.ThisargumentcontrolsthestateoftheXMLHTTPobject.Ifsettotrue,theobjectrunsasynchrounously,meaningthatallotherJavaScriptcodecontinueswhiletheobjectisloading.Whilethisisagoodthinginmanycircumstances,ifweimplementedithereourcodewouldreturnbeforeourfilewasdoneloading.Sincewewantourcodetowaituntilthisfileiscomplete,wesetthisthirdargumenttofalse,thuspausingourJavaScriptexecutionuntilwearereadytocontinue.

WhenthecodeisevaluatedfromtheresponseText,itsexecutedinthelimitedscopeoftheloadScriptfunctionandbecauseofthis,noneofthesefunctionswillbeavailableoutsideoftheloadScriptfunction.Inorderdogetaroundthis,theforloopaddseachfunctiontothewindowobject,thusmakingitgloballyavailable.

Itsimportanttonotethatonlyscriptsonthesameserverasthecurrentpagecanbecalledinthismanner.ThisisinherenttotheXMLHTTPObjectandisanecessarymeasuretoincreasegeneralbrowsersecurity.


评论


亲,登录后才可以留言!