En términos generales, si todo el código JavaScript requerido se carga a la vez, la página web inicial se ralentizará, pero no es necesario utilizar muchos códigos cargados, y este desecho de rendimiento innecesario debe evitarse. Si desea cargar dinámicamente el código JavaScript, puede usar el modelo DOM para agregar un nodo <Script> en el documento HTML y establecer el atributo SRC de este nodo (es decir, un archivo de JavaScript de divulgación) al código JavaScript que debe cargarse dinámicamente.
Aquí hay un ejemplo de completar dicha función:
(1) Cree un nuevo archivo jsloaderTest.html
<html xmlns = "http://www.w3.org/1999/xhtml"> <fead> <meta http-equiv = "content-type" content = "text/html; charset = gb2312"/> <title> Ejemplo de la carga de código de javaScript en la demanda </título> <script " JsLoader () {this.load = function (url) {// Obtener todas las <script> etiquetas var ss = document.getElementsBytagName ("script"); // prueba si el archivo especificado ha sido incluido. Si se ha incluido, active el evento OnSuccess y regrese para (i = 0; i <ss.length; i ++) {if (ss [i] .src && ss [i] .src.indexof (url)! =-1) {this.onsuccess (); devolver; }} // Crear nodo de script y establecer sus atributos al archivo javascript de divulgación s = document.createElement ("script"); s.type = "text/javaScript"; S.Src = url; // Obtener nodo Head e inserte <script> en var head = document.getElementsBytagName ("Head") [0]; head.appendChild (s); // Obtenga su propia referencia var selfe = this; //For IE browser, use the readystatechange event to determine whether the load is successful//For other browsers, use the onload event to determine whether the load is successful//s.onload=s.onreadystatechange=function(){ s.onload=s.onreadystatechange=function(){ //In this function, this pointer refers to the s node object, not the JsLoader instance, //So you must use self to call the Evento de OnSuccess, lo mismo a continuación. if (this.readyState && this.readyState == "Carga") return; self.onsuccess (); } s.onerror = function () {head.removechild (s); self.onfailure (); }}; // Defina el evento de éxito de carga this.onsuccess = function () {}; // Defina el evento fallido this.onfailure = function () {}; } function btnClick () {// crea el objeto var jsLoader = new JSLoader (); // Defina el controlador de éxito de carga jsloader.onsuccess = function () {sayhello (); } // Definir el controlador de falla de carga jsloader.onfailure = function () {alert ("Falling de carga de archivo!"); } // comienza a cargar jsloader.load ("hello.js"); } </script> </head> <body> <label> <input type = "subt" name = "enviar" onClick = "javaScript: btnclick ()" valor = "cargando archivo javaScript"> </selt> </body> </html>(2) Cree un nuevo archivo Hello.js, incluido el siguiente código:
// función de documento javascript sayshello () {alert ("¡Hola mundo! Archivo JavaScript cargado con éxito"); } // JavaScript DocumentFunction Sayshello () {Alert ("¡Hola mundo! Archivo JavaScript cargado con éxito"); }