Code Monkey home page Code Monkey logo

lazyload's Introduction

LazyLoad

Note: LazyLoad is no longer being maintained. I'm not responding to issues or pull requests, since I don't use this project anymore and don't have time to work on it. Please feel free to fork it if you want to continue development on it.

LazyLoad is a tiny (only 966 bytes minified and gzipped), dependency-free JavaScript utility that makes it super easy to load external JavaScript and CSS files on demand.

Whenever possible, LazyLoad will automatically load resources in parallel while ensuring execution order when you specify an array of URLs to load. In browsers that don't preserve the execution order of asynchronously-loaded scripts, LazyLoad will safely load the scripts sequentially.

Use LazyLoad when you need a small, fast, safe dynamic JS or CSS loader, but don't need the overhead of dependency management or other extra functionality that larger script loaders provide.

Downloads

Usage

Using LazyLoad is simple. Just call the appropriate method -- css() to load CSS, js() to load JavaScript -- and pass in a URL or array of URLs to load. You can also provide a callback function if you'd like to be notified when the resources have finished loading, as well as an argument to pass to the callback and a context in which to execute the callback.

// Load a single JavaScript file and execute a callback when it finishes.
LazyLoad.js('http://example.com/foo.js', function () {
  alert('foo.js has been loaded');
});

// Load multiple JS files and execute a callback when they've all finished.
LazyLoad.js(['foo.js', 'bar.js', 'baz.js'], function () {
  alert('all files have been loaded');
});

// Load a CSS file and pass an argument to the callback function.
LazyLoad.css('foo.css', function (arg) {
  alert(arg);
}, 'foo.css has been loaded');

// Load a CSS file and execute the callback in a different scope.
LazyLoad.css('foo.css', function () {
  alert(this.foo); // displays 'bar'
}, null, {foo: 'bar'});

Supported Browsers

  • Firefox 2+
  • Google Chrome
  • Internet Explorer 6+
  • Opera 9+
  • Safari 3+
  • Mobile Safari
  • Android

Other browsers may work, but haven't been tested. It's a safe bet that anything based on a recent version of Gecko or WebKit will probably work.

Caveats

All browsers support parallel loading of CSS. However, only Firefox and Opera currently support parallel script loading while preserving execution order. To ensure that scripts are always executed in the correct order, LazyLoad will load all scripts sequentially in browsers other than Firefox and Opera. Hopefully other browsers will improve their parallel script loading behavior soon.

License

Copyright (c) 2011 Ryan Grove ([email protected]). All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

lazyload's People

Contributors

rgrove avatar valeriansaliou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lazyload's Issues

Add a .both() method to load CSS and JS in parallel, with a single callback

Could just be a wrapper around calls to .js() and .css(). Something like this:

function both(cssURLs, jsURLs, callback) {
  var cssDone, jsDone;

  function finish() {
    if (cssDone && jsDone) {
      callback();
    }
  }

  LazyLoad.css(cssURLs, function () { cssDone = 1; finish(); });
  LazyLoad.js(jsURLs, function () { jsDone = 1; finish(); });
}

The last script fails to load in IE10 when using back button.

I've noticed that when using the browser's back (or forward) button, the last script doesn't load properly. The code is as such:

<script type="text/javascript" src="Scripts/lazyload.js"></script>
<script type="text/javascript">
    LazyLoad.js(["Scripts/script1.js", "Scripts/script2.js", "Scripts/script3.js"], function() {
        InitializeApplication(); //Defined in script3.js
    }
</script>

This code works just fine normally, but when I use the browser's back/forward buttons, the last script in the list doesn't load and InitializeApplication is undefined. My workaround has been to add a dummy element to the end of the script list. The dummy script of course has no content therefore I don't care if it doesn't load properly. This problem occurs in IE10, but not in Firefox. Any thoughts?

Don't import the same resource multiple times

Hello,

I'm using the pushstate API to reload just one subtree of the DOM on each request while maintaining the <head> element untouched. Some pages of my site need some extra JS or CSS which I'm going to load also using lazyload. Since the user may visit the same page multiple times, the same resource is being included in the <head> over and over.

How should I detect if some resource is already present and, if it is, prevent LazyLoad o include the file?

[help] Page-based loading

There are a lot of JS loaders, really. But none of them, at least within documentation, addresses a problem I'm eager to solve. That is to use single <script> line per whole project which inits page-based loading of dependencies.

Let's create a simple project with index, portfolio, and contacts pages.

Microframework will help us with routing:

$app->get('/portfolio/',
    function () use ($app) {
        $prices = array(
              "price_mine"  => "90",
              "price_rival" => "120"
        );
        $app->render('portfolio.twig', $prices);
    })->name('portfolio');

Template engine will help us with rendering:

{% extends "base.twig" %}
{% block content %}
     <p>Aren't you sick and tired to pay {{price_rival}}…</p>.
{% endblock content %}

And the missing part in every page is <script src="/static/init.js"></script> that works as follows

  • all pages load jQuery from CDN or from my server as fallback,
  • index loads SoundManager to serve audio salutation,
  • portfolio loads Lightbox to serve images,
  • contacts loads Forms validator.

What's the best way to achieve it?
And how to do that with Lazyload whether it's possible?

Thank you in advance.
Warm regards from Russia, Alexander.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of rgrove/lazyload!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library rgrove/lazyload is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "rgrove/lazyload",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Binding context/scope

I'm using prototype js, binding context doesn't work properly.
i'm passing this for obj, but it doesn't work.
it's much simpler for me to apply context via bind(this) for callback function, don't it?

Add jshint support

It would be better to add jshint support. This keep the code consist across contributors.

Webkit issue if page has no style

A very minor issue. On webkit, I get a "Uncaught TypeError: Cannot read property 'href' of undefined" on line 320 in the poll() function, if the page has absolutely no style.

While the chance of a real website not having any style at all is slim to nil, I found this out when I was doing some quick testing in javascript and was using a quick plain HTML file (only has doctype, head and body).

This applies to the master branch. It doesn't affect 2.0.0

jQuery $(document).ready() called before scripts are loaded.

I am testing LazyLoad as a way of delivering multiple UI framework files through two simple js includes. This way, developers don't have to include 20 or more links in their pages and I can update the files without requiring them to update their code.

The issue I am running into in my tests is that a jQuery document ready call placed at the end of a file can get called before the library files are loaded. This happens almost all the time in my test page.

Two restrictions: IE9 is the sole browser and adding the document ready call in the LazyLoad callback function is not an option. I can't control how people will design their apps.

Here is a sample of my page structure. In this example the chosen call fails as

Object doesn't support property or method 'chosen'

Please let me know if there is a workaround to this issue.

Thanks!

<!DOCTYPE html>
<html>
    <head>
        <script src="/shared/lazyload/lazyload.js"></script>
        <script src="/js/loader/1.1/scriptloader.js?v=full"></script>
   </head>
   <body>Page Content.... <select id="foo"><option>Hello</option></select>
   <script>
      $(document).ready(function(){
      $("#foo").chosen() // <--this fails
      });
   </script>
</body>
</html>

scriptloader.js Looks like this:


    cssBase = ["/shared/Bootstrap/2.3.2/noIcon/css/bootstrap.min.css"
                , "/shared/Bootstrap/2.3.2/noIcon/css/bootstrap-responsive.css"
                , "/shared/Bootstrap/overrides/2013.7/bootstrap-override.css"
                , "/shared/Fonts/FontAwesome/3.2.0/css/font-awesome.min.css"
                , "/shared/Fonts/OpenSans/OpenSans.css"
                , "/Shared/DataTables/1.9.4/media/css/DT_bootstrap.css"
                , "/shared/DataTables/1.9.4/extras/ColReorder/media/css/ColReorder.css"
                , "/shared/DataTables/1.9.4/extras/ColVis/media/css/ColVis.css"
                , "/shared/DataTables/1.9.4/extras/TableTools/media/css/TableTools.css"
                , "/shared/Chosen/0.9.15/css/chosen.css"
                , "/shared/DatePicker/2013.7/css/datepicker.css"
                , "/shared/TimePicker/2013.7/css/bootstrap-timepicker.min.css"
                , "/shared/DateRangePicker/2013.7/daterangepicker.css"
                , "/shared/Slider/2013.7/css/slider.css"
                , "/shared/css/3.0/Core.css"
              ]


    jsBase = ["/shared/jQuery/1.10.1/jquery-1.10.1.min.js"
                , "/shared/Bootstrap/2.3.2/noIcon/js/bootstrap.min.js"
                , "/shared/Bootstrap/overrides/2013.7/bootstrap-nb-extend.js"
                , "/shared/DataTables/1.9.4/media/js/jquery.dataTables.min.js"
                , "/Shared/DataTables/1.9.4/media/js/DT_bootstrap.js"
                , "/shared/DataTables/1.9.4/extras/ColReorder/media/js/ColReorder.min.js"
                , "/shared/DataTables/1.9.4/extras/ColVis/media/js/ColVis.min.js"
                , "/shared/DataTables/1.9.4/extras/FixedColumns/media/js/FixedColumns.min.js"
                , "/shared/DataTables/1.9.4/extras/FixedHeader/js/FixedHeader.min.js"
                , "/shared/DataTables/1.9.4/extras/TableTools/media/js/TableTools.min.js"
                , "/shared/DataTables/1.9.4/extras/TableTools/media/js/ZeroClipboard.js"
                , "/shared/DatePicker/2013.7/js/bootstrap-datepicker.js"
                , "/shared/TimePicker/2013.7/js/bootstrap-timepicker.min.js"
                , "/shared/Moment/2.0.0/moment.min.js"
                , "/shared/DateRangePicker/2013.7/daterangepicker.js"
                , "/shared/Chosen/0.9.15/js/chosen.jquery.min.js"
                , "/shared/BootBox/3.2.0/bootbox.min.js"
                , "/shared/Slider/2013.7/js/bootstrap-slider.js"
             ]


    LazyLoad.css(cssBase);
    LazyLoad.js(jsBase);

Custom Attribute on Stylesheet/Script tag

Since I'm using Prefixfree, LazyLoad tends to affect use of the styles as it adds appropriate vendor prefixes to properties, and to disable it on separate stylesheets, I'd have to add the data-noprefix attribute.

load of js and css together when they are related

Using Lazyload to load asynchronouslsy js and css on onload event for some part of my pages that are not critical.

How can I get jss and css to load in parallel and still detect both have finished loaded ?

For now I can serialize by loading css first and js in the callback or opposite but not optimal ;-)

Array of js files not always loading in correct order in FF4

I have enjoyed using lazyload.js for a few months but discovered a problem with the release of firefox 4. The javascript files are not always loading in the same order that I specified in the array. The only way to get around this currently is to have do all my initialisation in the final call back function.

add custom charset support

lazyload is a very good product,
we are going to use it in chinese environment now, but it only supports utf8 charset when loading js/css files.
i know that utf8 is the best choice, but in our sites there is lots of old js/css files using non-unicode charsets such as gbk, gb2312, etc.
so i suggest to add custom charset support:

LazyLoad.js(['file1.js[charset=utf-8]', 'file2.js[charset=gbk]']);

or

LazyLoad.js([{
  src: 'file1.js'
  charset: 'utf-8'
}, {
  src: 'file2.js',
  charset: 'gbk'
}]);

Either one would be fine.

and here is the code for the first form:

// lazyload.js 2.0.3
// line 218 add:
var charset = '';
var match = url.match(/\[charset=([a-zA-Z0-9-]+)\]$/);
if (match) {
  charset = match[1];
  url = url.replace(match[0], '');
}
// line 230 change to:
if (charset != '') node.setAttribute('charset', charset);

Thanks

Nested loading not working in IE10

I made sure to grab the latest minified version of LazyLoad and test again before filing this issue.

I'm writing an application that does nested loading of JS files for development. I'm concatenating and minifying all those scripts into a single file for production. In development, this is what my LazyLoad loading looks like:

LazyLoad.js([
    './dev/js/lib/jquery.js',
    './dev/js/lib/json2.js',
    './dev/js/lib/swfobject.js',
    './dev/js/lib/web_socket.js'
], function(){
    LazyLoad.js([
        // dependent on jQuery
        './dev/js/lib/underscore/underscore.js',
        './dev/js/lib/backbone/backbone.js',

        // bootstrap modules
        './dev/js/lib/bootstrap/bootstrap-affix.js',
        './dev/js/lib/bootstrap/bootstrap-dropdown.js',
        './dev/js/lib/bootstrap/bootstrap-tooltip.js',
        './dev/js/lib/bootstrap/bootstrap-alert.js',
        './dev/js/lib/bootstrap/bootstrap-modal.js',
        './dev/js/lib/bootstrap/bootstrap-transition.js',
        './dev/js/lib/bootstrap/bootstrap-button.js',
        './dev/js/lib/bootstrap/bootstrap-popover.js',
        './dev/js/lib/bootstrap/bootstrap-typeahead.js',
        './dev/js/lib/bootstrap/bootstrap-carousel.js',
        './dev/js/lib/bootstrap/bootstrap-scrollspy.js',
        './dev/js/lib/bootstrap/bootstrap-collapse.js',
        './dev/js/lib/bootstrap/bootstrap-tab.js'
    ], function(){
        //LazyLoad.js([
            // backbone classes; not added yet
            //
        //], function(){
            LazyLoad.js('./dev/js/_script');
        //});
    });
});

The above works in all browsers except IE10. The first 4 files above load, then all loading stops. So, underscore and backbone and all the files that depend on them are not being loaded.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.