CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-scriptjs

Asynchronous JavaScript loader and dependency manager for dynamic script loading

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

$script.js

$script.js is an asynchronous JavaScript loader and dependency manager with an impressively lightweight footprint. It allows you to load script resources on-demand from any URL without blocking other resources (CSS and images), while providing sophisticated dependency management capabilities for complex web applications.

Package Information

  • Package Name: scriptjs
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install scriptjs

Core Imports

For ES modules:

import $script from "scriptjs";

For CommonJS:

const $script = require("scriptjs");

For browser (global):

<script src="https://cdn.jsdelivr.net/npm/scriptjs@2.5.9/dist/script.js"></script>

When using Ender.js:

// Access via ender methods
$.script(/* ... */);
$.require(/* ... */);
$.ready(/* ... */);
$.getScript(/* ... */);

Basic Usage

// Load a single script
$script('path/to/script.js', function() {
  // Script is loaded and ready
});

// Load multiple scripts in parallel
$script(['jquery.js', 'plugin.js'], function() {
  // Both scripts are loaded
});

// Load scripts with dependency management
$script(['jquery.js', 'plugin.js'], 'bundle');
$script('app.js').ready('bundle', function() {
  // App runs after bundle is ready
});

Architecture

$script.js is built around several key concepts:

  • Asynchronous Loading: Scripts load in parallel without blocking page rendering
  • Dependency Management: Named bundles allow complex dependency relationships
  • State Tracking: Internal state management tracks loading progress and readiness
  • Chainable API: Most methods return the $script object for method chaining
  • Path Configuration: Global path and URL argument configuration for easier project management

Capabilities

Script Loading

Core functionality for loading JavaScript files asynchronously.

/**
 * Load JavaScript files asynchronously
 * @param paths - Single path string or array of paths
 * @param idOrDone - Bundle ID string or completion callback function
 * @param optDone - Optional completion callback when idOrDone is an ID
 * @returns $script object for chaining
 */
function $script(
  paths: string | string[],
  idOrDone?: string | (() => void),
  optDone?: () => void
): typeof $script;

Usage Examples:

// Load single script with callback
$script('app.js', function() {
  console.log('App loaded');
});

// Load multiple scripts
$script(['utils.js', 'config.js'], function() {
  console.log('Utils and config loaded');
});

// Load with bundle ID
$script(['jquery.js', 'plugin.js'], 'bundle');

// Load with ID and callback
$script('critical.js', 'critical', function() {
  console.log('Critical script loaded');
});

Direct Script Creation

Bypass path configuration and load scripts directly.

/**
 * Create and load a script element directly (bypasses path configuration)
 * @param path - Script URL
 * @param callback - Completion callback
 */
$script.get(path: string, callback: () => void): void;

Usage Example:

$script.get('https://cdn.example.com/library.js', function() {
  console.log('External library loaded');
});

Sequential Loading

Load scripts in a specific order (synchronous dependency chain).

/**
 * Load scripts in sequential order
 * @param scripts - Array of script paths to load in order
 * @param id - Bundle identifier for the ordered group
 * @param done - Completion callback
 */
$script.order(scripts: string[], id: string, done?: () => void): void;

Usage Example:

$script.order(['base.js', 'extension.js', 'app.js'], 'ordered', function() {
  console.log('All scripts loaded in order');
});

Path Configuration

Set a base path for relative script URLs.

/**
 * Set base path for relative script URLs
 * @param basePath - Base path to prepend to relative URLs
 */
$script.path(basePath: string): void;

Usage Example:

$script.path('/js/modules/');
$script(['dom', 'event'], function() {
  // Loads /js/modules/dom.js and /js/modules/event.js
});

URL Arguments

Add query string parameters to all script URLs for cache-busting.

/**
 * Set URL arguments to append to all script URLs
 * @param queryString - Query string to append (without leading ?)
 */
$script.urlArgs(queryString: string): void;

Usage Example:

$script.urlArgs('v=1.2.3&bust=' + Date.now());
$script('app.js'); // Loads app.js?v=1.2.3&bust=1234567890

Dependency Management

Wait for named dependencies before executing callbacks.

/**
 * Execute callback when dependencies are ready
 * @param deps - Single dependency ID or array of IDs
 * @param ready - Callback to execute when dependencies are ready
 * @param req - Optional error callback with missing dependencies
 * @returns $script object for chaining
 */
$script.ready(
  deps: string | string[],
  ready: () => void,
  req?: (missing: string[]) => void
): typeof $script;

Usage Examples:

// Wait for single dependency
$script.ready('jquery', function() {
  // jQuery is ready
});

// Wait for multiple dependencies
$script.ready(['jquery', 'utils'], function() {
  // Both jQuery and utils are ready
});

// With error handling
$script.ready(['required', 'optional'], function() {
  console.log('All dependencies ready');
}, function(missing) {
  console.log('Missing dependencies:', missing);
  // Load missing dependencies
  missing.forEach(dep => $script(dep + '.js', dep));
});

// Chaining ready calls
$script
  .ready('jquery', function() {
    console.log('jQuery ready');
  })
  .ready('bootstrap', function() {
    console.log('Bootstrap ready');
  });

Manual Completion

Manually mark a dependency as complete without loading a file.

/**
 * Manually mark a dependency as complete
 * @param id - Dependency identifier to mark complete
 */
$script.done(id: string): void;

Usage Example:

// In a plugin file that depends on jQuery
$script.ready('jquery', function() {
  // Define plugin here
  window.MyPlugin = { /* ... */ };
  
  // Mark this plugin as done
  $script.done('my-plugin');
});

// In main app
$script('jquery.js', 'jquery');
$script('my-plugin.js'); // Will call $script.done('my-plugin') internally
$script.ready('my-plugin', function() {
  // Use MyPlugin
});

Advanced Usage Patterns

Complex Dependency Management

// Load core libraries
$script('jquery.js', 'jquery');
$script('lodash.js', 'lodash');

// Load plugins that depend on core libraries
$script('jquery-plugin.js').ready('jquery', function() {
  // jQuery plugin code here
  $script.done('jquery-plugin');
});

// Load app that depends on everything
$script('app.js').ready(['jquery', 'lodash', 'jquery-plugin'], function() {
  // Start the application
});

Lazy Loading with Error Handling

const dependencyMap = {
  charts: 'charts.js',
  analytics: 'analytics.js',
  social: 'social-widgets.js'
};

$script.ready(['charts', 'analytics'], function() {
  // Both charts and analytics are ready
  initDashboard();
}, function(missing) {
  // Load missing dependencies
  missing.forEach(function(dep) {
    if (dependencyMap[dep]) {
      $script(dependencyMap[dep], dep);
    }
  });
});

Configuration for Large Projects

// Set up base configuration
$script.path('/assets/js/');
$script.urlArgs('v=' + window.APP_VERSION);

// Load core modules
$script(['core/utils', 'core/config', 'core/api'], 'core');

// Load feature modules
$script(['features/dashboard', 'features/reports'], 'features');

// Initialize application
$script.ready(['core', 'features'], function() {
  window.App.init();
});

Browser Compatibility

  • Internet Explorer 6+
  • Opera 10+
  • Safari 3+
  • Chrome 1+
  • Firefox 2+

Error Handling

$script.js handles loading errors gracefully:

  • Failed script loads still trigger callbacks
  • onerror events are handled to prevent hanging
  • Duplicate file requests are deduplicated automatically
  • Missing dependencies can be detected and handled via $script.ready error callbacks

docs

index.md

tile.json