PxLoader.js基于JavaScript的HTML5应用程序预加载库

发布于 2017-06-29 10:20:04 字数 15129 浏览 7751 评论 0

PxLoader是一个JavaScript库,用于帮助你实现图片、声音等各种文件的预加载功能,你需要对你的网站一个特定的动作,例如你需要预先显示一个用户界面或开始游戏,这时候可以预先加载一些资源,你可以使用它来创建一个HTML5游戏和网站预载。

它让您通过提供进度和完成事件来监视下载状态,并允许您对下载项目的顺序进行优先级排序。您甚至可以标记文件组,然后按标记对下载或注册事件进行优先级排序。

我们创造了HTML5版本与 Cut the Rope 都能很好的工作,可以预加载图像和声音文件类型的资源,我们需要为游戏,但它的设计是与任何类型的文件或其他网络行为的可扩展性和工作。

开始使用

1、下载脚本并将文件放在站点的JavaScript目录中。你需要的文件是:

  • PxLoader.js 主要库文件
  • PxLoaderImage.js 图像文件下载,如果你想下载图像文件
  • PxLoaderSound.js 音频文件下载,如果你想下载音频文件
  • PxLoaderVideo.js 视频文件下载,如果想下载视频文件
  • 任何你写的或在本页下载插件部分

声音文件下载依赖于 SoundManager 2 ,实际上PxLoader.js总是会延时下载文件,通过 SoundManager 2 我们可以选择如何下载基于无论是使用Flash或HTML5的音频文件。

2、将文件引入到你的网页中

<script src="js/PxLoader.js"></script>

3、选择性的添加你需要的插件,引入到你的网页中

<!- images -->
<script src="js/PxLoaderImage.js"></script>

<!- sounds -->
<script src="js/PxLoaderSound.js"></script>

在绘制画布之前下载图像

在HTML5画布上绘制图像之前,必须先加载它们。在这个例子中,我们在绘制图片之前等待3张图片下载。

// Create the loader and queue our 3 images. Images will not 
// begin downloading until we tell the loader to start. 
var loader = new PxLoader(), 
    backgroundImg = loader.addImage('images/headerbg.jpg'), 
    treesImg = loader.addImage('images/trees.png'), 
    ufoImg = loader.addImage('images/ufo.png'); 
 
// callback that will be run once images are ready 
loader.addCompletionListener(function() { 
    var canvas = document.getElementById('sample1-canvas'), 
        ctx = canvas.getContext('2d'); 
 
    ctx.drawImage(backgroundImg, 0, 0); 
    ctx.drawImage(treesImg, 0, 104); 
    ctx.drawImage(ufoImg, 360, 50); 
}); 
 
// begin downloading images 
loader.start();

图像加载进度条

HTML5游戏通常下载大量的图像。在本例中,我们将显示加载进度,而游戏加载100个图像。我们已经配置了我们的服务器来延迟每个图像1秒来模拟大的图像,这样你就可以观看进度了。别担心,你的浏览器会并行下载大量的图片,所以演示实际上不会花100秒。

// delay each image and append the timestamp to prevent caching 
var baseUrl = 'http://thinkpixellab.com/pxloader' + 
        '/slowImage.php?delay=1&time=' + new Date, 
    $log = $('#sample2-log').val(''), 
    $progress = $('#sample2-progress').text('0 / 100'), 
    loader = new PxLoader(); 
 
// add 100 images to the queue 
for(var i=0; i < 100; i++) { 
    // this time we'll create a PxLoaderImage instance instead of just 
    // giving the loader the image url 
    var pxImage = new PxLoaderImage(baseUrl + '&i=' + i); 
 
    // we can add our own properties for later use 
    pxImage.imageNumber = i + 1; 
 
    loader.add(pxImage); 
} 
 
// callback that runs every time an image loads 
loader.addProgressListener(function(e) { 
 
    // log which image completed 
    $log.val($log.val() + 'Image ' + e.resource.imageNumber + ' Loaded\r'); 
 
    // scroll to the bottom of the log 
    $log.scrollTop($log[0].scrollHeight); 
 
    // the event provides stats on the number of completed items 
    $progress.text(e.completedCount + ' / ' + e.totalCount); 
}); 
 
loader.start();

分组加载图像

许多HTML5站点需要为应用程序的几个不同部分下载资源。PxLoader让你的标签和优先的资源。对于这个例子,我们假设我们需要一组图像来绘制游戏菜单和游戏的第二组图像。因为我们需要先显示菜单,我们首先开始下载这些图片。PxLoader可以对很多听众提供进度更新,将更新和统计范围只有标签听众感兴趣的设置。

// delay each image and append the timestamp to prevent caching 
var baseUrl = 'http://thinkpixellab.com/pxloader' + 
        '/slowImage.php?delay=1time=' + new Date, 
    $log = $('#sample3-log').val(''), 
    $menuProgress = $('#sample3-menuProgress').text('0 / 50'), 
    $gameProgress = $('#sample3-gameProgress').text('0 / 50'), 
    $totalProgress = $('#sample3-totalProgress').text('0 / 100'), 
    loader = new PxLoader(); 
 
// queue 50 images for each section 
var addImagesForTag = function(tag, $progress) { 
    for(var i=0; i < 50; i++) { 
        var imageUrl = baseUrl + '&i=' + i + '&tag=' + tag; 
            pxImage = new PxLoaderImage(imageUrl, tag); 
        pxImage.imageNumber = i + 1; 
        loader.add(pxImage); 
    } 
 
    // add a listener to update progress for the tag 
    loader.addProgressListener(function(e) { 
        $progress.text(e.completedCount + ' / ' + e.totalCount); 
    }, tag); // scope listener to the current tag only 
}; 
 
addImagesForTag('menu', $menuProgress); 
addImagesForTag('game', $gameProgress); 
 
// listen to every event to update total progress 
loader.addProgressListener(function(e) { 
 
    // log which image completed 
    var line = ' Image ' + e.resource.imageNumber + 
        ' Loaded [' + e.resource.tags[0] + ']\r'; 
    $log.val($log.val() + line); 
 
    // scroll to the bottom of the log 
    $log.scrollTop($log[0].scrollHeight); 
 
    // the event provides stats on the number of completed items 
    $totalProgress.text(e.completedCount + ' / ' + e.totalCount); 
}); 
 
// start downloading images for tags in prioritized order 
loader.start(['menu', 'game']);

加载一组音频文件

对于这个示例,我们将加载5个音频剪辑。一旦所有的声音都准备好了,我们将展示一组可以点击播放每一个声音的图像。

PxLoaderSound 插件的依赖 SoundManager2 加载和播放音频文件。首先,添加 SoundManager2 和 PxLoaderSound 脚本引用:

<script src="soundManager2.js"></script>
<script src="PxLoaderSound.js"></script>

接下来,你需要初始化的SoundManager。以下是我们使用的设置:

// initialize the sound manager 
soundManager.url = 'soundManager2/'; 
soundManager.flashVersion = 9; 
soundManager.useHighPerformance = true; // reduces delays 
 
// reduce the default 1 sec delay to 500 ms 
soundManager.flashLoadTimeout = 500; 
 
// mp3 is required by default, but we don't want any requirements 
soundManager.audioFormats.mp3.required = false; 
 
// flash may timeout if not installed or when flashblock is installed 
soundManager.ontimeout(function(status) { 
    // no flash, go with HTML5 audio 
    soundManager.useHTML5Audio = true; 
    soundManager.preferFlash = false; 
    soundManager.reboot(); 
}); 
 
soundManager.onready(function() { 
    // ok to show the button to run the sound sample 
    $('#sample4-run').show(); 
});

最后,这里是加载和播放每个音频剪辑的代码:

var soundNames = ['cow', 'pig', 'tractor', 'dino', 'r2d2'], 
    loader = new PxLoader(), 
    i, len, url; 
 
// queue each sound for loading 
for(i=0, len = soundNames.length; i < len; i++) { 
 
    // see if the browser can play m4a 
    url = 'audio/' + soundNames[i] + '.m4a'; 
    if (!soundManager.canPlayURL(url)) { 
 
        // ok, what about ogg? 
        url = 'audio/' + soundNames[i] + '.ogg'; 
        if (!soundManager.canPlayURL(url)) { 
            continue; // can't be played 
        } 
    } 
 
    // queue the sound using the name as the SM2 id 
    loader.addSound(soundNames[i], url); 
} 
 
// listen to load events 
loader.addProgressListener(function(e) { 
 
    // show the icon once a sound has loaded 
    var soundId = e.resource.sound.sID, 
        $icon = $('#' + soundId).addClass('ready'); 
 
    // play the sound when the icon is clicked 
    $icon.click(function() { 
 
        // highlight the icon while playing 
        $icon.addClass('playing'); 
 
        soundManager.play(soundId, { 
            onfinish: function() { 
                $icon.removeClass('playing'); 
            } 
        }); 
    }); 
}); 
 
loader.start();

核心API文档

new PxLoader(settings)

You can override the default settings when creating a new PxLoader instance.

// create a loader using the default settings 
var loader = new PxLoader(); 
 
// create a loader with custom settings (shown with default values) 
var loader = new PxLoader({ 
        // how frequently we poll resources for progress 
        statusInterval: 5000, // every 5 seconds by default 
 
        // delay before logging since last progress change 
        loggingDelay: 20 * 1000, // log stragglers after 20 secs 
 
        // stop waiting if no progress has been made in the moving time window 
        noProgressTimeout: Infinity // do not stop waiting by default 
    }); 

add(resource)

Add a resource to the the loading queue. This generic method allows PxLoader to handle any type of resource that has a PxLoader plugin.

// add an image with a url 
loader.add(new PxLoaderImage('/image1.png')); 
 
// add an image with a single tag 
loader.add(new PxLoaderImage('/image2.png', 'tag1')); 
 
// image with multiple tags 
loader.add(new PxLoaderImage('/image3.png', ['tag1', 'tag2']); 
 
// image with a priority (relative to another resource with the same tag) 
loader.add(new PxLoaderImage('/image4.png', ['tag1', 'tag2'], 1); 

Plugins may also add a convenience method to PxLoader which makes adding a new resource a little easier and more concise.

// The PxLoaderImage plugin provides addImage which returns the img element 
// which can be used once the image has been downloaded 
var imgElement1 = loader.addImage('/image1.png'); 
    imgElement2 = loader.addImage('/image2.png', 'tag1'); 

addProgressListener(callback, tags)

Registers a callback that will be called anytime an event occurs for a resource with the specified tag(s). If the tags parameter is omitted then progress updates will be provided for every resource.

// log the name of every resource as its loaded 
loader.addProgressListener(function(e) { 
    console.log(e.resource.getName()); 
}); 
 
// the callback function receives an event object: 
var sampleEvent = { 
 
    // the updated resource 
    resource: {} // the resource parameter provided to loader.add() 
 
    // status for the updated resource 
    loaded: true, 
    error: false, 
    timeout: false, 
 
    // stats for all resources that match the listener's tags 
    completedCount: 42, 
    totalCount: 100 
}; 

addCompletionListener(callback, tags)

Works in the same way as the progress listener API, except instead of receiving updates for each change you are notified once everything completes.

// log when all resources have completed 
loader.addCompletionListener(function(e) { 
    console.log('Ready to go!'); 
}); 

log(showAll)

Writes a list of resources to the browser console. If showAll is true then all resources are logged, otherwise resources that have completed (loaded, error, or timeout) are omitted.

// write a list of resources we are still waiting for 
loader.log(); 

isBusy()

Returns true if the loader is still waiting for some resources to complete.

start(orderedTags)

Starts downloading all queued resources. Resources are ordered and started by tag first and then by priority. Its important to register all event listeners before calling start() because its possible for the loader to complete very quickly if resources are cached.

// start loading resources according to resource priority alone 
loader.start(); 
 
// start resources by tag first and then by priority 
loader.start(['tag1', 'tag2']); 

插件

Images

PxLoaderImage loads images using JavaScript <image> elements. We listen to load and readystate change events. Some browsers won't send events for cached images so we also check the iscomplete status during the periodic poll initiated by the loader. Errors are reported to the loader, and details can be retrieved from the img element's errors property.

SoundManager 2

PxLoaderSound loads audio using the SoundManager2 library. We're fans of this great little library because it supports HTML5 audio when available and falls back to flash when necessary.

Videos

Samples showing how to use this plugin are coming soon.

Plugin API

Writing a plugin so PxLoader can track another resource type is pretty easy. There are just a few functions that a resource should implement to communicate with the loader. Here is a skeleton that you can use to start.

function PxLoaderResource(url, tags, priority) { 
    var self = this; 
        loader = null; 
 
    // used by the loader to categorize and prioritize 
    this.tags = tags; 
    this.priority = priority; 
 
    // called by PxLoader to trigger download 
    this.start = function(pxLoader) { 
        // we need the loader ref so we can notify upon completion 
        loader = pxLoader; 
 
        // set up event handlers so we send the loader progress updates 
 
        // there are 3 possible events we can tell the loader about: 
        // loader.onLoad(self);    // the resource loaded 
        // loader.onError(self);   // an error occured 
        // loader.onTimeout(self); // timeout while waiting 
 
        // start downloading 
    }; 
 
    // called by PxLoader to check status of image (fallback in case 
    // the event listeners are not triggered). 
    this.checkStatus = function() { 
        // report any status changes to the loader 
        // no need to do anything if nothing has changed 
    }; 
 
    // called by PxLoader when it is no longer waiting 
    this.onTimeout = function() { 
        // must report a status to the loader: load, error, or timeout 
    }; 
 
    // returns a name for the resource that can be used in logging 
    this.getName = function() { 
        return url; 
    } 
} 

Get Involved

We'd love to hear what you think about PxLoader. It's a work in progress and we'd welcome any suggestions or code contributions. You can fork us on Github.

There are also lots of opportunities to extend PxLoader to handle additional resource types. Video (contributed!) and JSON are a few we'd love to see. Please remember that not just some, but "all your resource are belong to us".

Happy loading!

相关链接

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84961 人气
更多

推荐作者

娇女薄笑

文章 0 评论 0

biaggi

文章 0 评论 0

xiaolangfanhua

文章 0 评论 0

rivulet

文章 0 评论 0

我三岁

文章 0 评论 0

薆情海

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文