Dynamically load the required js files using ajax

Source: Internet
Author: User

I am used to using java. in java, a class can be directly imported, so I want to achieve this effect when doing javascript.
Some time ago, I used dojo. The function of dojo. require in it was very good. I looked at the code and got dizzy. There were a lot of things ~ You can also write a simple one by yourself. dojo. require can introduce the package and I will only import one js file.
Document. write, the execution order is incorrect. This is the import at the end, and we always need to import the js in the previous execution. In this way, the execution will report "XXX undefined ", it's about order.
Next, I want to use ajax synchronization (Note: It is not asynchronous) to call remote js files. The problem here is that when we want JavaScript files, we do not use absolute paths, it is the relative path. Which of the following is the reference for the relative path? You can use the file that calls js as a reference, or the js file that implements the call function as a reference. Here, I choose to write a js file to call other js files as needed, select it for reference. After some modifications, the path problem is solved. However, the data read from the Chinese there will be garbled problem, fortunately we do things with UTF-8 (because to internationalization), so here avoided.
After the remote js content is obtained, it will be executed. After eval is executed, it is found that the content defined in remote js cannot be obtained, we found that there was a problem with the context scope of eval execution. What we wanted was to execute js in the window object, huh? Is there any method for window? A: A window.exe cScript method is available. OK. Try it. If yes, yeah ~ Later, I found that in firefox, I could not use the program executor execScript, I found the program, and used the Program program eval. the method is similar to window.exe cScript in ie. However, when only window. eval is used, there may be problems in ie, so they are used together.
Below is the js that implements remote js security call: env. js. I am used to writing js with oo. Copy codeThe Code is as follows :/**
* @ Author zxub 2006-06-1
* Status information display class, defined by var Status = new function (), which can be statically referenced
* Generally, it is function Status (). In this way, the methods in the method cannot be referenced statically and must be referenced through objects.
*/
Var Status = new function ()
{
This. statusDiv = null;

/**
* Initialization Status display Layer
*/
This. init = function ()
{
If (this. statusDiv! = Null)
{
Return;
}
Var body = document. getElementsByTagName ("body") [0];
Var div = document. createElement ("div ");
Div. style. position = "absolute ";
Div. style. top = "50% ";
Div. style. left = "50% ";
Div. style. width = "280px ";
Div. style. margin = "-50px 0 0-100px ";
Div. style. padding = "15px ";
Div. style. backgroundColor = "#353555 ";
Div. style. border = "1px solid # CFCFFF ";
Div. style. color = "# CFCFFF ";
Div. style. fontSize = "14px ";
Div. style. textAlign = "center ";
Div. id = "status ";
Body. appendChild (div );
Div. style. display = "none ";
This. statusDiv = document. getElementById ("status ");
}

/**
* Set status information
* @ Param _ message: Information to be displayed
*/
This. showInfo = function (_ message)
{
If (this. statusDiv = null)
{
This. init ();
}
This. setStatusShow (true );
This. statusDiv. innerHTML = _ message;
}

/**
* Set whether the status layer is displayed.
* @ Param _ show: boolean value. true indicates display, and false indicates not display.
*/
This. setStatusShow = function (_ show)
{
If (this. statusDiv = null)
{
This. init ();
}
If (_ show)
{
This. statusDiv. style. display = "";
}
Else
{
This. statusDiv. innerHTML = "";
This. statusDiv. style. display = "none ";
}
}
}

/**
* @ Author zxub
* Classes used to store channel names and communication objects. Different Channel names can be used to differentiate communication objects.
*/
Function HttpRequestObject ()
{
This. chunnel = null;
This. instance = null;
}

/**
* @ Author zxub
* Communication processing class, which can be referenced statically
*/
Var Request = new function ()
{
This. showStatus = true;

// Communication Cache
This. httpRequestCache = new Array ();

/**
* Create a new communication object
* @ Return a new communication object
*/
This. createInstance = function ()
{
Var instance = null;
If (window. XMLHttpRequest)
{
// Mozilla
Instance = new XMLHttpRequest ();
// Some versions of Mozilla may encounter errors when processing the content returned by the server that does not contain the XML mime-type header. Therefore, make sure that the returned content contains text/xml Information.
If (instance. overrideMimeType)
{
Instance. overrideMimeType = "text/xml ";
}
}
Else if (window. ActiveXObject)
{
// IE
Var MSXML = ['msxml2. XMLHTTP.5.0 ', 'Microsoft. xmlhttp', 'msxml2. XMLHTTP.4.0', 'msxml2. XMLHTTP.3.0 ', 'msxml2. xmlhttp'];
For (var I = 0; I <MSXML. length; I ++)
{
Try
{
Instance = new ActiveXObject (MSXML [I]);
Break;
}
Catch (e)
{
}
}
}
Return instance;
}

/**
* Get a communication object
* If no channel name is specified, the default channel name is "default"
* If no communication class is required in the cache, create one and put it in the Communication Class cache.
* @ Param _ chunnel: channel name. If this parameter does not exist, the default value is "default"
* @ Return a communication object, which is stored in the communication Cache
*/
This. getInstance = function (_ chunnel)
{
Var instance = null;
Var object = null;
If (_ chunnel = undefined) // The channel name is not specified.
{
_ Chunnel = "default ";
}
Var getOne = false;
For (var I = 0; I <this. httpRequestCache; I ++)
{
Object = HttpRequestObject (this. httpRequestCache [I]);
If (object. chunnel ==_chunnel)
{
If (object. instance. readyState = 0 | object. instance. readyState = 4)
{
Instance = object. instance;
}
GetOne = true;
Break;
}
}
If (! GetOne) // if the object is not in the cache, create
{
Object = new HttpRequestObject ();
Object. chunnel = _ chunnel;
Object. instance = this. createInstance ();
This. httpRequestCache. push (object );
Instance = object. instance;
}
Return instance;
}

/**
* The client sends a request to the server.
* @ Param _ url: Request Purpose
* @ Param _ data: the data to be sent.
* @ Param _ processRequest: The function used to process the returned result. It can be defined elsewhere and requires a parameter, that is, the communication object to be processed.
* @ Param _ chunnel: channel name. The default value is "default"
* @ Param _ asynchronous: Specifies whether to process data asynchronously. The default value is true, that is, asynchronous processing.
*/
This. send = function (_ url, _ data, _ processRequest, _ chunnel, _ asynchronous)
{
If (_ url. length = 0 | _ url. indexOf ("? ") = 0)
{
Status. showInfo ("the request failed because the target is empty. Please check! ");
Window. setTimeout ("Status. setStatusShow (false)", 3000 );
Return;
}
If (this. showStatus)
{
Status. showInfo ("the request is being processed. Please wait ");
}
If (_ chunnel = undefined | _ chunnel = "")
{
_ Chunnel = "default ";
}
If (_ asynchronous = undefined)
{
_ Asynchronous = true;
}
Var instance = this. getInstance (_ chunnel );
If (instance = null)
{
Status. showInfo ("the browser does not support ajax. Please check! ")
Window. setTimeout ("Status. setStatusShow (false)", 3000 );
Return;
}
If (_ asynchronous = true & typeof (_ processRequest) = "function ")
{
Instance. onreadystatechange = function ()
{
If (instance. readyState = 4) // judge the object status
{
If (instance. status = 200) // The information has been returned successfully. Start to process the information.
{
_ ProcessRequest (instance );
Status. setStatusShow (false );
Request. showStatus = true;
}
Else
{
Status. showInfo ("the page you requested has an exception. Please check it! ");
Window. setTimeout ("Status. setStatusShow (false)", 3000 );
}
}
}
}
// _ Add a time-changed parameter to the url to prevent requests from being sent to the server due to the same request cached by the browser
If (_ url. indexOf ("? ")! =-1)
{
_ Url + = "& requestTime =" + (new Date (). getTime ();
}
Else
{
_ Url + = "? RequestTime = "+ (new Date (). getTime ();
}
If (_ data. length = 0)
{
Instance. open ("GET", _ url, _ asynchronous );
Instance. send (null );
}
Else
{
Instance. open ("POST", _ url, _ asynchronous );
Instance. setRequestHeader ("Content-Length", _ data. length );
Instance. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
Instance. send (_ data );
}
If (_ asynchronous = false & typeof (_ processRequest) = "function ")
{
_ ProcessRequest (instance );
If (Request. showStatus)
{
Status. setStatusShow (false );
}
Else
{
Request. showStatus = true;
}
}
}

/**
* Requests are continuously sent at intervals. They are only used for asynchronous processing and only for GET.
* @ Param _ interval: Request interval, in milliseconds
* @ Param _ url: request address
* @ Param _ processRequest: The function used to process the returned result. It can be defined elsewhere and requires a parameter, that is, the communication object to be processed.
* @ Param _ chunnel: channel name. The default value is "defaultInterval". This parameter is optional.
*/
This. intervalSend = function (_ interval, _ url, _ processRequest, _ chunnel)
{
Var action = function ()
{
If (_ chunnel = undefined)
{
_ Chunnel = "defaultInterval ";
}
Var instance = Request. getInstance (_ chunnel );
If (instance = null)
{
Status. showInfo ("the browser does not support ajax. Please check! ")
Window. setTimeout ("Status. setStatusShow (false)", 3000 );
Return;
}
If (typeof (_ processRequest) = "function ")
{
Instance. onreadystatechange = function ()
{
If (instance. readyState = 4) // judge the object status
{
If (instance. status = 200) // The information has been returned successfully. Start to process the information.
{
_ ProcessRequest (instance );
}
Else
{
Status. showInfo ("the page you requested has an exception. Please check it! ");
Window. setTimeout ("Status. setStatusShow (false)", 3000 );
}
}
}
}
// _ Add a time-changed parameter to the url to prevent requests from being sent to the server due to the same request cached by the browser
If (_ url. indexOf ("? ")! =-1)
{
_ Url + = "& requestTime =" + (new Date (). getTime ();
}
Else
{
_ Url + = "? RequestTime = "+ (new Date (). getTime ();
}
Instance. open ("GET", _ url, true );
Instance. send (null );
}
Window. setInterval (action, _ interval );
}
}

Var Env = new function ()
{
This. funcList = new Array ();

This. envPath = null;

This. getPath = function ()
{
This. envPath = document. location. pathname;
This. envPath = this. envPath. substring (0, this. envPath. lastIndexOf ("/") + 1 );
Var _ scripts = document. getElementsByTagName ("script ");
Var _ envPath = null;
Var _ scriptSrc = null;
For (var I = 0; I <_ scripts. length; I ++)
{
_ ScriptSrc = _ scripts [I]. getAttribute ("src ");
If (_ scriptSrc & _ scriptSrc. indexOf ("env. js ")! =-1)
{
Break;
}
}
If (_ scriptSrc! = Null)
{
If (_ scriptSrc. charAt (0) = '/')
{
This. envPath = _ scriptSrc. substr (0, _ scriptSrc. length-6 );
}
Else
{
This. envPath = this. envPath + _ scriptSrc. substr (0, _ scriptSrc. length-6 );
}
}
}
This. getPath ();

/**
* Obtain the required js files as needed
* @ Param _ jsName: js file path. If it is a relative path, it is the relative path corresponding to env. js. You can also use an absolute path.
* @ Param _ language: the language in which the returned function is processed. The default value is JScript, which can be left blank.
*/
This. require = function (_ jsName, _ language)
{
Var _ absJsName = null;
If (_ jsName. charAt (0) = '/')
{
_ AbsJsName = _ jsName;
}
Else
{
_ AbsJsName = this. envPath + _ jsName;
}
If (! Env. funcList [_ absJsName])
{
Env. funcList [_ absJsName] = "finished ";
Var processJs = function (_ instance)
{
// Make judgments for firefox compatibility
If (_ language! = Undefined)
{
If (window.exe cScript)
{
Window.exe cScript (_ instance. responseText, _ language );
}
Else
{
Window. eval (_ instance. responseText, _ language );
}
}
Else
{
If (window.exe cScript)
{
Window.exe cScript (_ instance. responseText );
}
Else
{
Window. eval (_ instance. responseText );
}
}
}
Request. showStatus = false;
Request. send (_ absJsName, "", processJs, "", false );
}
}

/**
* The function adds a script block after the script block is applied.
* The execution sequence of document. write in the script block is determined.
*/
This. getJs = function (_ jsName)
{
If (! Env. funcList [_ jsName])
{
Env. funcList [_ jsName] = "finished ";
Document. write ('<scr' + 'ept type = "text/javascript" src = "'+ _ jsName +'"> </'+ 'Scr' + 'ipt'> ');
}
}
}

/**
* Unexecuted script block processing on the remote page after ajax calls
*/
Function reloadJs (_ language)
{
Var _ c = document. getElementsByTagName ("SCRIPT ");
For (var I = 0; I <_ c. length; I ++)
{
If (_ c [I]. src)
{
Var _ s = document. createElement ("script ");
_ S. type = "text/javascript ";
_ S. src = _ c [I]. src;
// Compatible with firefox. Do not use _ c [0]. insertAdjacentElement ("beforeBegin", _ s)
_ C [0]. parentNode. insertBefore (_ s, _ c [0]);
_ C [I]. parentNode. removeChild (_ c [I]);
}
Else if (_ c [I]. text)
{
If (_ language! = Undefined)
{
If (window.exe cScript)
{
Window.exe cScript (_ c [I]. text, _ language );
}
Else
{
Window. eval (_ c [I]. text, _ language );
}
}
Else
{
If (window.exe cScript)
{
Window.exe cScript (_ c [I]. text );
}
Else
{
Window. eval (_ c [I]. text );
}
}
}
}
}

When you need to reference other js files, add such as Env. require ("cookie. js "), or Env. require ("/common/cookie. js "), whether the relative path or absolute path is preferred, Env. require can be used in page templates or js files, but env must be ensured during execution. js is explicitly introduced. Multiple times Env. require is the same js (either relative or absolute), and will only be loaded for the first time, so it will not be repeated.
Different from individual applications, you can modify the subject idea.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.