uu.snippet 入門(2) 複数の部品を一つのsnippet に

uu.snippetで「やりましょう」、Widgetの作り方入門 - latest log の続きです。

uu.snippet は、複数の部品(コードブロックや関数)を一つのファイルにまとめ上げることが可能です。

実行環境によってスタイルを微調整する

MediaQuery を古いブラウザで実現する方法は色々と存在しますが、uu.snippet でも目的は果たせます。

// media.css.js

// 外部からスニペット内部の関数を参照できるように、return でオブジェクトを返している
return {
    pc: pcBrowserStyle,
    mobile: mobileBrowserStyle
};

function pcBrowserStyle() { // PC用のスタイルを返す関数
    return <>
<style>
div.widget {
    width: {{arg.pc.width}}px;
    border: 1px solid black;
}
</style>
</>
}

function mobileBrowserStyle() { // モバイル用のスタイルを返す関数
    return <>
<style>
div.widget {
    width: {{arg.mobile.width}}px;
    border: 1px solid black;
    padding: 5px;
    -webkit-border-radius: 10px;
    -webkit-box-shadow: 5px 5px 5px gray;
}
</style>
</>
}

ページへの埋め込みと、呼び出しはこのようにします。

<!DOCTYPE html><html lang="ja"><head><meta charset="utf-8" />
<title></title>
<style>
.widget { position: absolute; }
</style>
<script src="uupaa.js"></script>
<script id="multisnippet" src="media.css.js" type="text/html"></script>
<script>
uu.ready(function() {
  var arg = {
     pc:     { width: 800 }, // PCなら幅を800pxに
     mobile: { width: Math.max(uu.viewport.innerWidth - 20, 320) } // モバイルは画面幅で調整
  };
  if (uu.viewport.orientation !== 0) {
     arg.mobile.width *= 0.75; // 横持ちなら、調整したり
  }
  var styles = uu.snippet("multisnippet", arg); // スニペットのロード

  // スニペット内の関数を呼び分け。style要素をhead要素に追加
  uu.head(uu.ver.mobile ? styles.mobile()
                        : styles.pc());
});
</script></head><body>

<div class="widget">
aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge
aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge
aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge aaaaa hoge hoge hoge
</div>

</body></html>

snippet は、ページに埋め込むこともできます

無作法ですが、html要素の外に置いても機能します。

<!DOCTYPE html><html lang="ja"><head><meta charset="utf-8" />
<title></title>
<style>
.widget { position: absolute; }
</style>
<script src="uupaa.js"></script>
<script id="multisnippet" src="media.css.js" type="text/html"></script>
<script>
uu.ready(function() {
  var arg = {};
  uu.body(uu.snippet("multisnippet", arg));
  uu.body(uu.snippet("snippet1", arg));
  uu.body(uu.snippet("snippet2", arg));

});
</script></head><body>
<!-- なにか -->
<!-- なにか -->
<!-- なにか -->


<script id="snippet1" type="text/html">
    return <>
<style></style>
</>
</script>


</body></html>


<script id="snippet2" type="text/html">
    return <>
<style></style>
</>
</script>