Use jquery to dynamically load javascript to reduce server pressure

Source: Internet
Author: User
Tags getscript

Fortunately, jQuery provides a built-in utility function. $ getScript () provides us with this method. To implement the dynamic functions of the webpage. Let's take a look at the syntax of this function:

$. GetScript (url, callback)

Obtains the script specified by the url parameter and sends a GET request to the specified server.

Parameters
URL () to obtain the URL of the script file.

Callback (Function) optional functions call the functions in the script file after loading

The specific implementation process is

Load text from resource

| If the string is successful

Returns an XHR instance to obtain the script.

How to use it? See the following method.

Create a new. js script file
Copy codeThe Code is as follows:
Var testVar = 'new JS loaded! ';
Alert (testVar );
Function newFun (dynParam)
{
Alert (You must passed '+ dynParam + 'as parameter .');
}

HTML code
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> $. getScript Example </title>
<Script type = "text/javascript" src = ".../jquery. js"> </script>
<Script type = "text/javascript">
$ (Function ()
{
$ ('# LoadButton'). click (function (){
$. GetScript ('new. js', function (){
NewFun ('"Checking new script"'); // This function is in new. js. click it to run this function.
});
});
});
</Script>
</Head>
<Body>
<Button type = "button" id = "loadButton"> Load </button>
</Body>
</Html>

In the above Code, we create a new. js script file and call it when the button function is triggered in the body part. The advantage of doing so is to reduce the pressure on the server, which is highly recommended.

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.