LoginSignup
6
2

More than 5 years have passed since last update.

外部js,cssを動的に読込(PageSpeedInsights対策)

Posted at

メモとして

Google PageSpeed Insights
https://developers.google.com/speed/pagespeed/insights/?hl=ja

これでスピードを測った時に驚愕な数値を出したので、それの対策用に入れました。
入れたことにより20~30ポイント程度上昇しました。

本当はこんな小細工に頼らずにできるのが一番なんでしょうけど。。

動的に読込むスクリプト

index.js
window.site = {};
lazy_list = null;
value = null;
temp = null;
cnt = 'ture';

site.onReady = function() {
  wid = $(window).width();

  // 読み込むファイルを並べる
  lazy_list = [
    '/xxxxxxxxx.css',
    '/xxxxxxxxx.js',
    '/xxxxxxxxx.js',
  ];
  require_onload(lazy_list);
}

function require_onload( arg ) {
  if(cnt == 'ture'){
    if (is_array(arg)){
      var element = [];
      for(var i=0; i<arg.length; i++){
        if ( arg[i].match(/\.css$/) ){
          add_child_css(arg[i]);
        }
        else if ( arg[i].match(/\.js$/) ){
          add_child_js(arg[i]);
        }
          else{ alert('check url : ' + arg[i]) }
      }
    }
    else{
      if ( arg.match(/\.css$/) ){
        add_child_css(arg);
      }
      else if ( arg.match(/\.js$/) ){
        add_child_js(arg);
      }
      else{ alert('check url : ' + arg[i]) }
    }
    cnt = 'false';
  }
}
function add_child_js(src){
  var js_element = document.createElement("script");
  js_element.src = src;
  // document.body.appendChild(element);
  var h = document.getElementsByTagName('head')[0];
  h.parentNode.insertBefore(js_element, h);
}
function add_child_css(src){
  var css_element = document.createElement('link');
  css_element.rel  = 'stylesheet';
  css_element.href = src;
  // document.body.appendChild(css_element);
  var h = document.getElementsByTagName('head')[0];
  h.parentNode.insertBefore(css_element, h);
}
function is_array(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2