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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zoltanradics/gtm-loader

v1.0.6

Published

Google Tag Manager (GTM) script loader

Readme

Google Tag Manager Loader

npm version License: MIT

A lightweight, promise-based Google Tag Manager (GTM) script loader for modern web applications. Built with TypeScript and powered by @zoltanradics/async-script-loader.

Features

  • Promise-based API - Know exactly when GTM is loaded and ready
  • TypeScript Support - Full type definitions included
  • Lightweight - Only 0.57 kB (gzipped: 0.38 kB)
  • Modern ESM - ES Module format for optimal tree-shaking
  • Zero Dependencies - Only one peer dependency for script injection
  • Customizable DataLayer - Support for custom dataLayer names
  • Browser Environment Detection - Automatic checks for safe loading

Installation

npm install @zoltanradics/gtm-loader

Or with yarn:

yarn add @zoltanradics/gtm-loader

Or with pnpm:

pnpm add @zoltanradics/gtm-loader

Usage

Basic Usage

import googleTagManagerLoader from '@zoltanradics/gtm-loader';

// Load GTM with your container ID
googleTagManagerLoader('GTM-XXXXXX')
  .then(() => {
    console.log('GTM loaded successfully!');
    // GTM is now ready, tags will start firing
  })
  .catch((error) => {
    console.error('Failed to load GTM:', error);
  });

With Async/Await

import googleTagManagerLoader from '@zoltanradics/gtm-loader';

async function initializeAnalytics() {
  try {
    await googleTagManagerLoader('GTM-XXXXXX');
    console.log('GTM loaded successfully!');
  } catch (error) {
    console.error('Failed to load GTM:', error);
  }
}

initializeAnalytics();

Custom DataLayer Name

import googleTagManagerLoader from '@zoltanradics/gtm-loader';

// Use a custom dataLayer name
googleTagManagerLoader('GTM-XXXXXX', 'myCustomDataLayer')
  .then(() => {
    console.log('GTM loaded with custom dataLayer!');
  });

React Example

import { useEffect } from 'react';
import googleTagManagerLoader from '@zoltanradics/gtm-loader';

function App() {
  useEffect(() => {
    googleTagManagerLoader('GTM-XXXXXX')
      .then(() => console.log('GTM loaded'))
      .catch((error) => console.error('GTM error:', error));
  }, []);

  return <div>Your App</div>;
}

Vue Example

<script setup>
import { onMounted } from 'vue';
import googleTagManagerLoader from '@zoltanradics/gtm-loader';

onMounted(async () => {
  try {
    await googleTagManagerLoader('GTM-XXXXXX');
    console.log('GTM loaded');
  } catch (error) {
    console.error('GTM error:', error);
  }
});
</script>

API

googleTagManagerLoader(containerId, dataLayerKey?)

Loads the Google Tag Manager script asynchronously.

Parameters

  • containerId (string, required) - Your GTM container ID (e.g., 'GTM-XXXXXX')
  • dataLayerKey (string, optional) - Custom dataLayer name (defaults to 'dataLayer')

Returns

  • Promise<void> - Resolves when GTM script is successfully loaded, rejects on error

Throws

  • Error - If called in a non-browser environment (no window object)
  • Error - If containerId is undefined or invalid

How It Works

  1. Environment Check - Verifies execution in a browser environment
  2. DataLayer Initialization - Creates or uses existing window.dataLayer with GTM start event
  3. Script Injection - Uses @zoltanradics/async-script-loader to load gtm.js
  4. Promise Resolution - Returns promise that resolves when script loads successfully

Browser Support

Works in all modern browsers that support:

  • ES2020
  • ES Modules
  • Promises
  • Native async/await

Demo

Check out the live demo to see the loader in action with real-time logging and dataLayer monitoring.

Development

Setup

# Install dependencies
npm install

# Start development server
npm run dev

# Build the library
npm run build

# Run demo in development
npm run demo:dev

# Build demo for deployment
npm run demo:build

Project Structure

├── src/
│   └── google-tag-manager-loader.ts  # Main source file
├── demo/
│   ├── index.html                    # Demo page
│   ├── demo.js                       # Demo logic
│   └── style.css                     # Demo styles
├── dist/                             # Built library (generated)
├── dist-demo/                        # Built demo (generated)
└── package.json

Why Use This Loader?

Instead of Direct Script Tag

<!-- Traditional approach -->
<script>(function(w,d,s,l,i){...})(window,document,'script','dataLayer','GTM-XXXXXX');</script>

Benefits of using this loader:

  • ✅ Promise-based - Know when GTM is ready
  • ✅ Error handling - Catch loading failures
  • ✅ TypeScript types - Full IDE support
  • ✅ Tree-shakeable - Optimal bundle size
  • ✅ Testable - Easy to mock in tests
  • ✅ Modern - Follows JavaScript best practices

Related Packages

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support


License

MIT © Zoltan Radics

Made with ❤️ by Zoltan Radics