19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptから別のjavascriptの処理を呼出し実行する

Last updated at Posted at 2019-03-27

経緯、目的

会社で運用しているWebシステムのつくりが悪く、
ほとんど同じ処理にも関わらず、画面ごとに別々のjsを作って呼び出しているため、
改修案件が発生すると何本も同じような修正が必要になり、開発コストも障害リスクも高い。
そのため、共通した部分の処理を切り出して別のjsファイルを作成し、
それぞれのファイルから必要に応じて呼び出すようにできないかと考えた。

試したこと

共通関数func_a.jsの関数の処理結果を個別処理func_b.js経由で取得し、画面main.htmlに表示する。
というごくごく簡単なモノですが・・・
※共通関数func_a.jsの処理(関数)は、windowオブジェクトのグローバル変数としてセットする。

ソース

main.html
<!doctype html>
<html lang="ja">
  <head>
    <meta charset="Shift_JIS">
    <title>JS共通化サンプル</title>
    <meta name="description" content="">
    <meta name="keywords" content=",,,,">
    <meta name="viewport" content="width=device-width">
    <script src="js/func_a.js"></script>
    <script src="js/func_b.js"></script>
  </head>
  <body>
    <h2>JS共通化サンプル</h2>
    <div>func_a.jsより、func_b.jsの処理を呼び出し実行する</div><br>
    <input type="button" value="テスト" onClick="pushBtn()"/><br>
    
  </body>
</html>
func_a.js
(function() {
    function hoge() {
        fuga = 'fuga';
        return fuga;
    }
    window.hogeLib= window.hogeLib|| {};
    window.hogeLib.hoge = hoge;
})();
func_b.js
function pushBtn() {
    // func_a.jsのhogeを呼び出す処理
    var hoge = window.hogeLib.hoge();

    //文字列がアラートに表示される。
    alert(hoge);
};

画面イメージ

◆画面表示時
image.png

◆「テスト」ボタン押下時(アラート表示)
WS000013.JPG

結果

ごくごく簡単なサンプルですが、あるjsから別のjsの処理を呼び出すことができることが確認できました。
(そんなコトをするより、各jsの差異を取り込んだ1本のjsに集約した方がむしろ早いし分かり易い、
という意見が社内的には強いですが。)

19
21
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
19
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?