js utility method record - js dynamically loads css and js script files

Posted by NCllns on Sat, 07 Dec 2019 16:00:23 +0100

js utility method record dynamic loading css/js

1. Dynamically load js file to head tag and execute callback
Method call: dynamicLoadJs(' http://www.yimo.link/static/j... ', function(){alert('loading succeeded')});

    /**
     * Load JS dynamically
     * @param {string} url Script address
     * @param {function} callback  Callback function
     */
    function dynamicLoadJs(url, callback) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
        if(typeof(callback)=='function'){
            script.onload = script.onreadystatechange = function () {
                if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete"){
                    callback();
                    script.onload = script.onreadystatechange = null;
                }
            };
        }
        head.appendChild(script);
    }

2. Dynamically load the css file to the head tag and execute the callback
Method call: dynamiclodcss (' http://www.yimo.link/static/c... ', function(){alert('loading succeeded')})

    /**
     * Load CSS dynamically
     * @param {string} url Style address
     */
    function dynamicLoadCss(url) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.type='text/css';
        link.rel = 'stylesheet';
        link.href = url;
        head.appendChild(link);
    }

3. Dynamically load script file
Reference resources: http://www.cnblogs.com/yuanke...

     /**
     * Loading css script dynamically
     * @param {string} cssText css style
     */
    function loadStyleString(cssText) {
        var style = document.createElement("style");
        style.type = "text/css";
        try{
            // firefox, safari, chrome and Opera
            style.appendChild(document.createTextNode(cssText));
        }catch(ex) {
            // In the early browser of IE, the cssText attribute of stylesheet attribute of style element is needed
            style.styleSheet.cssText = cssText;
        }
        document.getElementsByTagName("head")[0].appendChild(style);
    }
    // test
    var css = "body{color:blue;}";
    loadStyleString(css);
    
    
    
    /**
     * Loading js script dynamically
     * @param {string} code js Script
     */
    function loadScriptString(code) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        try{
            // firefox, safari, chrome and Opera
            script.appendChild(document.createTextNode(code));
        }catch(ex) {
            // In the early browser of IE, the text property of script was used to specify javascript code.
            script.text = code;
        }
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    // test
    var text = "function test(){alert('test');}";
    loadScriptString(text);
    test();
    
    

4. Dynamically load iframe to body tag and execute callback
Method call: dynamicloduframe (' http://www.yimo.link ', function(){alert('loading succeeded')}, '');

   /**
   * Load Iframe dynamically
   * @param {string} url Script address
   * @param {function} callback  Callback function
   * @param {string} style  Loading style
   */
  function dynamicLoadIframe(url,callback,style) {
    var body = document.getElementsByTagName('body')[0];
    var iframe = document.createElement('iframe');
    iframe.src = url;
    iframe.style=style||'display:none;width:0px;height:0px;';
    if(typeof(callback)=='function'){
        iframe.onload = iframe.onreadystatechange = function () {
            if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                callback();
                iframe.onload = iframe.onreadystatechange = null;
            }
        };
    }
    body.appendChild(iframe);
  }

5. Download / open app in M station
Method test: openApp('ios page ',' * *. apk','metools://home ');

    function openApp(iosDownUrl,andDownUrl,appUrl) {
        var ua = navigator.userAgent.toLowerCase();    
        if (/iphone|ipad|ipod/.test(ua)) {//ios jump to store
          window.location.href = iosDownUrl;
          return;
        } 
        if(ua.indexOf("micromessenger") > -1){//Wechat cannot open other app s
          window.location.href = andDownUrl;
          return;
        }
        if (/android/.test(ua)) {//Android tries to call app
          if(!appUrl){
            console.log('Not specified to open App,May refer to http://www.oschina.net/code/snippet_256033_35330/');
            return;
          }
          var su = appUrl;//"metools://index"; / / custom protocol
          var n = setTimeout(function () {
            window.location.href = andDownUrl
          }, 500);
          var r = document.createElement("iframe");
          r.src = su;
          r.onload = function () {
            console.log('iframe load')
            clearTimeout(n);
            r.parentNode.removeChild(r);
            window.location.href = su;
          };
          r.setAttribute("style", "display:none;");
          document.body.appendChild(r);
          return;
        }
        window.location.href = andDownUrl;
      }

6.query parameter conversion
Reference resources: https://github.com/nicejade/a...
query parameter to object

export function query(search) {
  let str = search || window.location.search
  let objURL = {}

  str.replace(new RegExp('([^?=&]+)(=([^&]*))?', 'g'), ($0, $1, $2, $3) => {
    objURL[$1] = $3
  })
  return objURL
}

7. Use: query('?v=1')
Object to query parameter

function queryString(url, query) {
  let str = []
  for (let key in query) {
    str.push(key + '=' + query[key])
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}

Topics: Front-end Javascript Firefox IE Attribute