<! Doctype html> <Html> <Head> <Meta charset = "gbk"> <Title> JS asynchronous loading </title> </Head> <Body> <Input id = "loadInput" type = "text" placeholder = "enter url"/> <Input id = "loadBtn" type = "submit" value = "Load"/> <Script type = "text/javascript"> Var head = document. getElementsByTagName ("head") [0], LoadBtn = document. getElementById ("loadBtn "), LoadInput = document. getElementById ("loadInput "), Load, loaded = []; Load = function (url ){ Var f = true, N; If (/. js $/I. test (url )){ N = document. createElement ("script "); N. setAttribute ("type", "text/javascript "); N. setAttribute ("src", url ); N. setAttribute ("async", true ); } Else if (/. css $/I. test (url )){ N = document. createElement ("link "); N. setAttribute ("type", "text/css "); N. setAttribute ("rel", "stylesheet "); N. setAttribute ("href", url ); Loaded [url] = true; } Else { F = false; Alert ("enter the correct type! "); } If (f ){ /** * Determine whether the element is successfully loaded. */ N. onload = n. onreadystatechange = function (){ If (! This. readyState | this. readyState = "loaded" | this. readyState = "complete "){ Loaded [this. getAttribute ("src")] = true; N. onload = n. onreadystatechange = null; } }; Head. appendChild (n ); } }; LoadBtn. onclick = function (){ Var url = loadInput. value; If (loaded [url]) { Alert ("do not reload! ") } Else { Load (url ); } }; </Script> </Body> </Html> |