Implementation of dynamic addition of JS file

Source: Internet
Author: User

AMD and CMD-based module development and on-demand loading have brought convenience to our development process.

Today to share a project in the development of an on-demand loading JS method, not much, direct PS code

/** * JS loading to the top * @param {String} URL * @param {boolean} request and Load * @param {Function} fn * @return {Boolean} */function re        Quirejs (URL, multi, fn) {if (typeof multi = = ' function ') {var _temp = fn;        fn = multi;    Multi = _temp;    } var ss = document.getElementsByTagName (' script ');    var loaded = false; for (var i = 0; I<SS. length; i++) {if (ss[i].src && ss[i].getattribute (' src ')== URL) {Loaded= true; Break ; }} if (loaded) {if (fn && typeof fn!)= ' undefined '&& fn instanceof Function)            {fn ();        return false; }} var s= document.createelement (' script '),b= false; s.setattribute (' type ', ' text/javascript '); if (multi) {This.loadjs= fn; var noarg= Url.indexof ('? ') = =-1; S.setattribute (' src ', url + (noarg? '? ': ' & ') + ' callback=wysiwyg.loadjs '); } else {s.setattribute (' src ', url); S.onload= S.onreadystatechange = function() {if (!b && (!this.readystate | | this.readystate== ' Loaded ' | | this.readystate== ' complete ')) {b= true; if (fn && typeof fn! )= ' undefined '&& fn instanceof Function) fn ();    }        }; } document.getelementsbytagname (' head ') [0].appendchild (s);}

This method will check whether the page has introduced the need to introduce JS, if not, then load the JS, if already exist, do not load;

Implementation of dynamic addition of JS file

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.