How to dynamically load js files as needed

Source: Internet
Author: User
JavaScript is nothing more than introducing the script tag to the page, but when the project grows

JavaScript is nothing more than introducing the script tag to the page. But when the project grows, N JavaScript codes are introduced to a single page. merging a single file reduces the number of requests, however, the requested file volume is large. At this time, the best practice is to introduce components js and style dynamically as needed. After the file load is complete, call callback to run js. The code is still very simple.

1. Check whether the file load is complete. The loading status of ie is onreadystatechange, and the others are onload and onerror.

if(isie){Res.onreadystatechange = function(){if(Res.readyState == 'complete' || Res.readyState == 'loaded'){Res.onreadystatechange = null;      callback();       _self.loadedUi[modelName] = true;}}}else{Res.onload = function(){Res.onload = null;callback();_self.loadedUi[modelName] = true;}Res.onerror = function(){throw new Error('res error:' + modelName+'.js');}}

2. It is recommended that the names of all components be consistent, and callback calls are convenient. You can also add parameters as needed, such as requires, dependent on those files; style, true | false, whether to load the style, and so on.

3. You can also remove the script, style tag, and delete components.

(Function (window, undefined) {if (! Window. ui) {window. ui ={};}// dynamically load the js window of the ui. bus = {config: {version: window. config. version, cssPath: window. config. resServer + '/css/v3/Ui', jsPath: window. config. resServer + '/js/v2/Ui'}, loadedUi: {}, readyStateChange: function () {var ua = navigator. userAgent. toLowerCase (); return ua. indexOf ('msi')> = 0;}, loadRes: function (modelName, prames, callback) {var _ self = this; var Res = Document. createElement (prames. tagName); for (var k in prames) {if (k! = 'Tagname') {Res. setAttribute (k, prames [k], 0) ;}} document. getElementsByTagName ('head') [0]. appendChild (Res); if (this. readyStateChange () {Res. onreadystatechange = function () {if (Res. readyState = 'complete' | Res. readyState = 'loaded') {Res. onreadystatechange = null; callback (); _ self. loadedUi [modelName] = true ;}} else {Res. onload = function () {Res. onload = null; callback (); _ self. loadedUi [mo DelName] = true;} Res. onerror = function () {throw new Error ('res error: '+ modelName + '. js') ;}}, removeUi: function (modelName) {if (! ModelName) {return true}; this. loadedUi [modelName] = false; var head = document. getElementsByTagName ('head') [0]; var model_js = document. getElementById ('J _ model _ '+ modelName +' _ js'); var model_css = document. getElementById ('J _ model _ '+ modelName +' _ css '); if (model_js & model_css) {delete window. ui [modelName]; head. removeChild (model_js); head. removeChild (model_css); return true;} else {return false ;}}, LoadUi: function (modelName, callback, setting) {if (! ModelName) {return true}; callback = callback | function () {}; if (this. loadedUi [modelName] = true) {callback (); return true} var deafult_setting = {style: true, js: true, requires: []} for (var key in setting) {deafult_setting [key] = setting [key];} deafult_setting ['style'] = true & this. loadRes (modelName, {id: 'J _ model _ '+ modelName +' _ css ', name: modelName, tagName: 'link', type: 'TE Xt/css ', rel: 'stylesheet', href: this.config.css Path + '/' + modelName + '.css? V = '+ this. config. version}); deafult_setting ['js'] === true & this. loadRes (modelName, {id: 'J _ model _ '+ modelName +' _ js', name: modelName, tagName: 'script', type: 'text/javascript ', src: this. config. jsPath + '/' + modelName + '. js? V = '+ this. config. version}, callback); if (deafult_setting.requires.length> 0) {for (var I = 0, len = deafult_setting.requires.length; I <len; I ++) {this. loadUi (deafult_setting.requires [I]) ;}}}) (window)

Usage:

// load comment for feed    window.bus.loadUi('new_comment_feed', function(){        window.ui.new_comment_feed($("#J_newsList"));    },{        style : false,        requires:['emoticon','addFriend']    });    // load new yy ui    window.bus.loadUi('yy', function(){        window.ui.yy(options);    },{        style:false,        requires:['emoticon']    });    // load photoLightbox    window.bus.loadUi('photoLightbox', function(){        window.ui.photoLightbox(options.urlAjaxGetFriendPhoto, options.urlCommentOtherPhoto,$("#J_newsList"),options.myUid,options.myName);    });

This article is available at http://www.nowamagic.net/librarys/veda/detail/604.

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.