npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sygnas/resource-loader

v1.0.0

Published

シンプルで軽量なリソースローディングライブラリ

Downloads

3

Readme

ResourceLoader

シンプルで軽量なリソースローディングライブラリ。画像、動画、音声、JSON、テキストファイルなどの読み込みを管理し、進捗状況をイベントで通知します。

特徴

  • 🚀 軽量 - 依存関係なし、シンプルな実装
  • 📦 多様なリソース対応 - 画像、動画、音声、JSON、テキストなど
  • 📊 進捗管理 - リアルタイムで読み込み進捗を追跡
  • 🔗 メソッドチェーン - 直感的なAPI設計
  • 💪 TypeScript - 完全な型定義
  • 🎯 イベント駆動 - シンプルなイベントハンドラーAPI

インストール

npm install @sygnas/resource-loader

または

yarn add @sygnas/resource-loader

基本的な使い方

import { ResourceLoader } from '@sygnas/resource-loader';

const loader = new ResourceLoader();

// リソースを追加
loader.add('/images/photo1.jpg');
loader.add('/images/photo2.jpg');
loader.add('/data/config.json');

// 進捗イベントを監視
loader.on('progress', (percent, url) => {
  console.log(`進捗: ${Math.round(percent * 100)}%`);
  console.log(`読み込み完了: ${url}`);
});

// 完了イベントを監視
loader.on('complete', (results) => {
  console.log('すべての読み込みが完了しました', results);
});

// エラーイベントを監視
loader.on('error', (error, url) => {
  console.error(`エラー: ${url}`, error);
});

// 読み込みを開始
await loader.load();

プログレスバーとの連動

const loader = new ResourceLoader();
const progressBar = document.querySelector('.progress-bar');

// 画像を追加
const images = [
  '/images/hero.jpg',
  '/images/gallery1.jpg',
  '/images/gallery2.jpg',
];
images.forEach(url => loader.add(url));

// プログレスバーを更新
loader.on('progress', (percent) => {
  progressBar.style.width = `${percent * 100}%`;
});

// 完了時にローディング画面を非表示
loader.on('complete', () => {
  document.querySelector('.loading-screen').classList.add('hidden');
  document.querySelector('.main-content').classList.remove('hidden');
});

loader.load();

メソッドチェーン

const loader = new ResourceLoader();

loader
  .add('/image1.jpg')
  .add('/image2.jpg')
  .add('/image3.jpg')
  .on('progress', (percent) => {
    console.log(`${Math.round(percent * 100)}%`);
  })
  .on('complete', () => {
    console.log('完了');
  })
  .load();

複数リソースの一括追加

const loader = new ResourceLoader();

const urls = [
  '/images/photo1.jpg',
  '/images/photo2.jpg',
  '/videos/intro.mp4',
  '/data/config.json',
];

loader.addAll(urls);
loader.load();

Promiseとの組み合わせ

async function loadResources() {
  const loader = new ResourceLoader();
  
  return new Promise((resolve, reject) => {
    loader.addAll([
      '/image1.jpg',
      '/image2.jpg',
      '/data/config.json',
    ]);

    loader.on('progress', (percent) => {
      updateProgressBar(percent);
    });

    loader.on('complete', (results) => {
      resolve(results);
    });

    loader.on('error', (error, url) => {
      console.error(`読み込みエラー: ${url}`, error);
      // エラーが発生しても処理を継続
    });

    loader.load().catch(reject);
  });
}

// 使用例
await loadResources();
console.log('ページの準備が完了しました');

イベントリスナーの削除

const loader = new ResourceLoader();

const progressHandler = (percent, url) => {
  console.log(`${Math.round(percent * 100)}%`);
};

// イベントを登録
loader.on('progress', progressHandler);

// 特定のハンドラーを削除
loader.off('progress', progressHandler);

// すべてのcompleteハンドラーを削除
loader.off('complete');

API

コンストラクタ

new ResourceLoader(options?: LoaderOptions)

オプション

  • xhrImages (boolean): XHR経由で画像を読み込む(CORS対応)。デフォルトは false

メソッド

add(url: string): this

リソースを追加します。

addAll(urls: string[]): this

複数のリソースを一括で追加します。

on(event: string, callback: Function): this

イベントリスナーを登録します。

イベント:

  • progress(percent: number, url: string) - リソースが1つ読み込まれるたびに発火
  • complete(results: ResourceResult[]) - すべてのリソースの読み込みが完了したときに発火
  • error(error: Error, url: string) - エラーが発生したときに発火

off(event: string, callback?: Function): this

イベントリスナーを削除します。callbackを省略すると、そのイベントのすべてのリスナーが削除されます。

load(): Promise<ResourceResult[]>

読み込みを開始します。結果の配列を含むPromiseを返します。

getProgress(): number

現在の進捗率(0〜1)を取得します。

getLoadedCount(): number

読み込み済みのリソース数を取得します。

getTotalCount(): number

総リソース数を取得します。

reset(): void

ローダーをリセットします。

型定義

interface ResourceResult {
  url: string;           // リソースのURL
  data: any;            // 読み込まれたデータ
  type: ResourceType;   // リソースタイプ
  success: boolean;     // 読み込み成功フラグ
}

type ResourceType = 'image' | 'video' | 'audio' | 'json' | 'text' | 'blob';

対応リソース

  • 画像: .jpg, .jpeg, .png, .gif, .webp, .svg, .bmp
  • 動画: .mp4, .webm, .ogg, .mov
  • 音声: .mp3, .wav, .ogg, .aac
  • JSON: .json
  • テキスト: .txt, .md, .csv
  • その他: Blobとして読み込み

高度な使用例

必須リソースとオプショナルリソースの分離

// 必須リソース(最初に読み込む)
const criticalLoader = new ResourceLoader();
criticalLoader.addAll([
  '/images/logo.png',
  '/data/settings.json',
]);

criticalLoader.on('complete', () => {
  // 画面を表示
  showMainContent();
  
  // オプショナルリソースをバックグラウンドで読み込み
  const optionalLoader = new ResourceLoader();
  optionalLoader.addAll([
    '/images/background.jpg',
    '/videos/ambient.mp4',
  ]);
  optionalLoader.load();
});

criticalLoader.load();

カスタムプログレス表示

const loader = new ResourceLoader();
loader.addAll(imageUrls);

loader.on('progress', (percent, url) => {
  const loaded = loader.getLoadedCount();
  const total = loader.getTotalCount();
  
  document.querySelector('.progress-text').textContent = 
    `${loaded} / ${total} (${Math.round(percent * 100)}%)`;
  
  document.querySelector('.progress-bar').style.width = 
    `${percent * 100}%`;
});

loader.load();

ブラウザ対応

モダンブラウザ(ES2017+)に対応しています。

  • Chrome 55+
  • Firefox 52+
  • Safari 10.1+
  • Edge 15+

ライセンス

MIT

コントリビューション

プルリクエストを歓迎します!バグ報告や機能リクエストは、GitHubのIssuesからお願いします。

変更履歴

1.0.0

  • 初回リリース
  • イベント駆動API
  • 多様なリソースタイプのサポート
  • TypeScript対応