草庐IT

javascript - 快速图像加载方法,具有多个背景的低分辨率到高分辨率 - javascript 解决方案?

coder 2024-05-14 原文

background-image:url('images/bg1.png'), url('images/speed/bg1.jpg');

我正在尝试利用一个元素的多个背景图像选项来加载,首先,每个背景图像的快速、低分辨率版本在加载后将被更高质量的版本替换。

有什么有效的解决方案吗?

注:以下是一厢情愿而非实际问题;我认为这可能是一个很好的主题来固定查询。

作为附带问题,有没有人知道使用这种想法的方法,而不是让图像从低分辨率过渡到渲染,并带有某种噪声效果,如果你明白我要去哪里接着就,随即。就好像每个图像都从普通噪声平滑到高清,获得分辨率,直到它在加载时达到适当的水平。

我想我的意思是:“是否可以编写一个脚本来加载单个图像作为可变噪声,随着图像加载慢慢变得清晰,而不是从上到下加载 100% 分辨率? "

最佳答案

//
//  You have dozen of hd photos, and don't want to embed them right from the get go
//  in order to avoid 'interlaced' load, boost application load, etc.
//  Idea is to place lo-res photos, temporarily, in place where hd ones should go,
//  while downloading full quality images in the background.
//
//  People usualy do this kind of caching by attaching 'onload' event handler to off-screen
//  Image object ( created by new Image(), document.createElement('img'), or any
//  other fashion ), which gets executed natively by a browser when the event
//  ( 'onload' in this case ) occurs, and setting the '.src' property of an image to
//  the phisical path ( relative/absolute ) of an img to start the download process.
//  The script pressented here use that approach for multiple images,
//  and notifies of task done by running provided function.
//
//  So, solution is to provide locations of images you want to,
//  and get notified when they get fully downloaded, and cached by browser.
//  To do that you pass a function as 1st parameter to the fn below,
//  passing as many images as needed after it.
//
//  Code will scan through provided images keeping the ones that are actualy
//  image files( .jpeg, .png, .tiff, etc.), create 'off-screen' Image objects
//  and attach onload/onerror/onabort handler fn to each one( which will be called
//  when coresponding circumstance occurs ), and initiate loading by setting the
//  .src property of an Image object.
//
//  After the 'load-handler' has been called the number of times that coresponds to
//  number of images ( meaning the dload process is done ), script notifies you
//  of job done by running the function you provided as first argument to it,
//  additinaly passing images( that are cached and ready to go ) as
//  parameters to callback fn you supplied.
//
//  Inside the callback you do whatever you do with cached photos.
//
function hd_pics_dload( fn /* ,...hd-s */ ) {

    var
        n        = 0,   // this one is used as counter/flag to signal the download end
        P        = [],  // array to hold Image objects

                        // here goes the image filtering stuff part,
                        // all the images that pass the 'regex' test
                        // ( the ones that have valid image extension )
                        // are considerd valid, and are kept for download
        arg_imgs =  Array.prototype.filter.call(
                        Array.prototype.slice.call( arguments, 1 ),
                        function ( imgstr ) {
                            return ( /\.(?:jpe?g|jpe|png|gif|bmp|tiff?|tga|iff)$/i ).test( imgstr );
                        }
                    );


           // aborts script if no images are provided
           // runs passed function anyway

        if ( arg_imgs.length === 0 ) {
            fn.apply( document, arg_imgs );
            return arg_imgs;
        }


          // this part keeps track of number of 'load-handler' calls,
          // when 'n' hits the amount of given photos
          // provided callback is runned ( signaling load complete )
          // and whatever code is inside of it, it is executed.
          // it passes images as parameters to callback,
          // and sets it's context ( this ) to document object

        var hd_imgs_load_handler = function ( e ) {

            // logs the progress to the console
            console.log( e.type, ' -- > ', this.src );

            ( ++n === arg_imgs.length )
            && fn.apply( document, arg_imgs );

        };


         // this part loops through given images,
         // populates the P[] with Image objects,
         // attaches 'hd_imgs_load_handler' event handler to each one,
         // and starts up the download thing( by setting '.src' to coresponding image path )

    for (
        var i = 0,
        len   = arg_imgs.length;
        i < len;
        i++
    ) {
        P[i] = new Image;
        P[i].onabort = hd_imgs_load_handler;
        P[i].onerror = hd_imgs_load_handler;
        P[i].onload  = hd_imgs_load_handler;
        P[i].src     = arg_imgs[i];
    }

    // it gives back images that are about to be loaded
    return arg_imgs;

}
//
// use:

hd_pics_dload(

       // 1st provide a function that will handle photos once cached
    function () { console.log('done -> ', arguments ); },

       // and provide pics, as many as needed, here
       // don't forget to separate all parameters with a comma
    'http://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Flag_of_the_United_Nations.svg/2000px-Flag_of_the_United_Nations.svg.png',
    'http://upload.wikimedia.org/wikipedia/commons/e/e5/IBM_Port-A-Punch.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/7/7e/Tim_Berners-Lee_CP_2.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/2000px-NewTux.svg.png',
    'http://upload.wikimedia.org/wikipedia/commons/4/4c/Beekeeper_keeping_bees.jpg',
    'http://upload.wikimedia.org/wikipedia/commons/9/9a/100607-F-1234S-004.jpg'
);

//

关于javascript - 快速图像加载方法,具有多个背景的低分辨率到高分辨率 - javascript 解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906266/

有关javascript - 快速图像加载方法,具有多个背景的低分辨率到高分辨率 - javascript 解决方案?的更多相关文章

  1. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  5. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  6. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  7. ruby-on-rails - 在 ruby​​ .gemspec 文件中,如何指定依赖项的多个版本? - 2

    我正在尝试修改当前依赖于定义为activeresource的gem:s.add_dependency"activeresource","~>3.0"为了让gem与Rails4一起工作,我需要扩展依赖关系以与activeresource的版本3或4一起工作。我不想简单地添加以下内容,因为它可能会在以后引起问题:s.add_dependency"activeresource",">=3.0"有没有办法指定可接受版本的列表?~>3.0还是~>4.0? 最佳答案 根据thedocumentation,如果你想要3到4之间的所有版本,你可以这

  8. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  9. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  10. ruby - 使用多个数组创建计数 - 2

    我正在尝试按0-9和a-z的顺序创建数字和字母列表。我有一组值value_array=['0','1','2','3','4','5','6','7','8','9','a','b','光盘','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','','u','v','w','x','y','z']和一个组合列表的数组,按顺序,这些数字可以产生x个字符,比方说三个list_array=[]和一个当前字母和数字组合的数组(在将它插入列表数组之前我会把它变成一个字符串,]current_combo['0','0','0']

随机推荐