Skip to content

Exaload/battery-saver

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ Battery Saver

Intelligent animation and transition reduction based on device battery level

Battery Saver is a lightweight JavaScript library that automatically optimizes your website's performance by reducing animations, transitions, and other power-consuming visual effects based on the user's battery level. Perfect for improving battery life on mobile devices and laptops.

License Version

✨ Features

  • πŸ”‹ Automatic Battery Detection - Uses the Battery API to monitor device battery level
  • 🎨 Progressive Animation Reduction - Four modes: Normal, Medium, Low, and Critical
  • βš™οΈ Customizable Thresholds - Configure when different power-saving modes activate
  • πŸ’Ύ Persistent Settings - User preferences saved in localStorage
  • 🎯 CSS Utility Classes - Easy integration with existing projects
  • πŸ“± Mobile & Desktop Support - Works across all modern browsers
  • ⚑ Zero Dependencies - Pure vanilla JavaScript
  • πŸ”Œ Event-Driven - React to battery and mode changes
  • πŸš€ Easy Integration - Auto-initialize or manual control

πŸš€ Quick Start

1. Include the files

<!DOCTYPE html>
<html lang="en" data-battery-saver-auto>
<head>
    <link rel="stylesheet" href="battery-saver.css">
</head>
<body>
    <!-- Your content -->
    
    <script src="battery-saver.js"></script>
</body>
</html>

That's it! Battery Saver will automatically monitor battery levels and adjust animations accordingly.

2. See it in action

Open demo.html in your browser to see a live demonstration of all features.

πŸ“¦ What's Included

battery-saver/
β”œβ”€β”€ battery-saver.js      # Main library (12KB)
β”œβ”€β”€ battery-saver.css     # Optimized styles (6KB)
β”œβ”€β”€ demo.html             # Interactive demo
β”œβ”€β”€ USAGE.md              # Detailed documentation
β”œβ”€β”€ README.md             # This file
└── LICENSE               # MIT License

🎯 How It Works

Battery Saver monitors your device's battery level and automatically switches between four optimization modes:

🟒 Normal Mode (>50% or charging)

  • All animations work normally
  • Full GPU acceleration
  • All effects enabled

🟑 Medium Mode (30-50%)

  • Animations reduced to 0.5s
  • Transitions reduced to 0.3s
  • Parallax effects disabled

🟠 Low Mode (15-30%)

  • Animations reduced to 0.2s
  • Transitions reduced to 0.15s
  • Shadows and blur removed
  • Video autoplay disabled

πŸ”΄ Critical Mode (<15%)

  • All animations disabled
  • All transitions disabled
  • Maximum power saving

πŸ’‘ Usage Examples

Auto-Initialize

<html data-battery-saver-auto>

Manual Control

const batterySaver = new BatterySaver({
    enabled: true,
    thresholds: {
        critical: 15,
        low: 30,
        medium: 50
    }
});

// Listen to events
batterySaver.on('modeChange', (data) => {
    console.log('Battery mode:', data.currentMode);
});

batterySaver.on('batteryChange', (data) => {
    console.log('Battery level:', data.level + '%');
});

Custom Configuration

const batterySaver = new BatterySaver({
    thresholds: {
        critical: 10,  // More aggressive
        low: 25,
        medium: 60
    },
    updateInterval: 10000  // Check every 10 seconds
});

Enable/Disable

// Toggle on/off
batterySaver.toggle();

// Enable
batterySaver.enable();

// Disable
batterySaver.disable();

// Check status
if (batterySaver.isEnabled()) {
    console.log('Battery Saver is active');
}

🎨 CSS Integration

Automatic Classes

Battery Saver automatically applies these classes:

/* Applied when battery saving is active */
.battery-saver-active { }
.battery-saver-reduce-shadows { }
.battery-saver-reduce-blur { }
.battery-saver-reduce-gradients { }
.battery-saver-reduce-motion { }

HTML Attributes

<html data-battery-saver-mode="low">

CSS Custom Properties

:root {
    --battery-saver-animation-duration: 1s;
    --battery-saver-transition-duration: 0.3s;
}

/* Use in your styles */
.my-animation {
    animation-duration: var(--battery-saver-animation-duration);
}

Utility Classes

<!-- Opt-in to optimizations -->
<div class="battery-saver-enabled">...</div>

<!-- Exclude from battery saver -->
<div class="battery-saver-exclude">...</div>

πŸ“– API Reference

Methods

Method Description
init() Initialize Battery Saver
enable() Enable battery saving
disable() Disable battery saving
toggle() Toggle on/off
isEnabled() Check if enabled
getStatus() Get current status
setMode(mode) Manually set mode
updateThresholds(obj) Update thresholds
on(event, callback) Add event listener
off(event, callback) Remove event listener
destroy() Clean up instance

Events

Event Description Data
modeChange Fired when mode changes { previousMode, currentMode, modeConfig }
batteryChange Fired when battery updates { level, isCharging, mode }

🌐 Browser Support

Browser Support Battery API
Chrome βœ… βœ… 38+
Edge βœ… βœ… 79+
Firefox βœ… ⚠️ Behind flag
Safari βœ… ❌ Graceful fallback
Opera βœ… βœ… 25+

Note: On browsers without Battery API support, the library still works with manual mode control.

🎯 Best Practices

  1. Use GPU-accelerated properties: Prefer transform and opacity
  2. Provide fallbacks: Design with battery saving in mind
  3. Test on real devices: Battery behavior varies
  4. Respect user preferences: Honor prefers-reduced-motion
  5. Monitor performance: Use DevTools to verify improvements

πŸ“š Documentation

🀝 Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ’‘ Ideas for Improvement

We're always looking for ways to improve battery savings! Consider:

  • Adaptive Quality: Reduce image quality dynamically
  • Lazy Loading: Defer non-critical resources
  • Network Optimization: Reduce API calls on low battery
  • Video Quality: Lower video resolution automatically
  • Background Tasks: Pause background animations
  • Service Workers: Cache more aggressively
  • WebGL: Reduce polygon count or shader complexity

πŸ“ License

MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

  • Inspired by the need for better battery life on mobile devices
  • Built with web standards and best practices
  • Community-driven development

πŸ“ž Support


Made with ⚑ and ❀️ for a greener web

About

Simple battery saving script. Reduce animation frames, number of animations...

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors