jquery and JS dynamic loading of JS file example

Source: Internet
Author: User
Tags getscript script tag

If you load the script tag directly with jquery append, you will get an error. In addition to document.write, there are other better ways to dynamically load JS files.

1,jquery method


$.getscript ("./test.js"); Load JS file

$.getscript ("./test.js", function () {//Load test.js, after success, and execute callback function
Console.log ("Load JS file");
});

2,js method

<body>
</body>
<script type= "Text/javascript" >
function Loadscript (URL, callback) {
var script = document.createelement ("script");
Script.type = "Text/javascript";
if (typeof (callback)!= "undefined") {
if (script.readystate) {
Script.onreadystatechange = function () {
if (script.readystate = = "Loaded" | | | script.readystate = = "complete") {
Script.onreadystatechange = null;
Callback ();
}
};
} else {
Script.onload = function () {
Callback ();
};
}
}
script.src = URL;
Document.body.appendChild (script);
}

Loadscript ("Http://code.jquery.com/jquery-latest.js", function () {//load, and execute callback function
Alert ($ (window). Height ());
});

Loadscript ("Http://code.jquery.com/jquery-latest.js"); Load JS file
</script>

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.