EzDevInfo.com

yepnope.js

A Script Loader For Your Conditional Builds yepnope.js | A Conditional Loader For Your Polyfills! a conditional loader for your polyfills. only load the scripts that you need!

How to check if an asynchronously loaded script has finished loading in javascript

Using javascript to asynchronously download another javascript file.

I understand that this can be done by inserting a new script tag onto the page with the src attribute set to the file url.

I also need to run some code when the script is finished downloading. I've been using yepnope for this and they provide "callbacks" that execute when the script has finished downloading and executing.

How is this accomplished?

Thanks!


Source: (StackOverflow)

How can I use yepnope.js with $(document).ready() effectively?

I have been implementing the yepnope script loader as part of the modernizr.js library. I have successfully got jQuery to load and jQuery dependent scripts afterwards. I am new to asynchronous loading of resources, so it's a bit new to me. I have been searching around, but haven't had much luck with the following.

My question is what are your opinions on how to effectively replace the functionality of $(document).ready() when working with the yepnope.js framework.

My theory was to create a appropriately named function in my base library and then set that variable on my pages to an anonymous function containing my existing $(document).ready() code. This variable would then be called by yepnope after all the scripts had loaded in the complete callback.

Would you agree that this is a good way of doing it, or am I approaching this entirely the wrong way?

(For those unaware, the asynchronous nature of yepnope.js means that the document calls $ or jQuery before the yepnope loader has finished, throwing a "$ is undefined" error <- please correct me if that is wrong.)

First question, hope it's a good one.


Source: (StackOverflow)

Advertisements

Multiple conditions with yepnope

I use yepnope.js as a resource loaded. I want to execute code in my JS module only when all the dependencies for that module have been loaded. I do not want to load JS dependencies that already been loaded.

Suppose, I have dependencies D1.js and D2.js. I tried

yepnope({
    load: ['D1.js', 'D2.js],
    complete: function() {
        //execute my code here
    }
});

That works, but, resources are loaded every time, even if they were already loaded before.

If I do multiple tests like that:

yepnope([{
    test: $().d1,
    nope: 'D1.js'
},
{
    test: $().d2,
    nope: 'D2.js'
}]);

It's not clear where to put the overall completed function -- the one that runs after all the resources have been loaded.

Is it possible to do this with yepnope, or do I need to use a different component?

Thanks.


Source: (StackOverflow)

How would I (or should I) extend Modernizr.load() to preload images?

The idea is that the page /something/index.html is loaded. But, before I show it, its dependencies (css and images in this case) are preloaded.

Modernizr.load({
    load: ['/something/styles.css', '/something/image1.jpg'],
    complete: showFile
 });

I've looked into Paul Irish's "imagesLoaded" jQuery plug in, but I prefer the simplicity of using the loader I already have. I know YepNope (and Modernizr.load) aren't designer as generic preloaders, but I feel like this is the cleanest way to do this.

Would appreciate any thoughts on how to implement image preloading into a Modernizr/YepNope load script.

nz


Source: (StackOverflow)

Alternatives to YepNope and LabJS

I am wanting to load javascript and css files via a resource loader. I was originally using LabJs but I found YepNope more elegant and easier to work with in my scenario. However I am finding it devastatingly slow, which is odd as apparently it is comparable to LabJs in speed on most things.

One thing I do have are Etags which I am sure will slow everything down as its still requesting from the server rather than just working off the client cache.

Anyway there isnt much outside of the main YepNope site, and they havent released a new version with the fixes on their issues list in a while, so I was wondering what other options there are out there...

My requirements are:

  • Needs to load Css and Javascript
  • Needs to do them all in parallel
  • Can be loaded via Javascript

I wish YepNope was a bit more active but wanted to weigh up the other options...


Source: (StackOverflow)

YepNope (Modernizr) and Google Analytics

Im using the great async script loader yepnope.js (in Modernizr2).

My question is, what is the best way to incorporate the latset Google Analtics async code to yepnope (if at all)?

Google suggest this for the actual analytics code:

<html>

<head>
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-X']);
    _gaq.push(['_trackPageview']);
  </script>
</head>

<body>
  <p>Page Content</p>

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

  <p>Page Content</p>

  <script type="text/javascript">  (function() {
    var ga = document.createElement('script');     ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:'   == document.location.protocol ? 'https://ssl'   : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
   </script>
</body>
</html>

But in Modernizrs docs, they mention this:

// Give Modernizr.load a string, an object, or an array of strings and objects
Modernizr.load([
  // Presentational polyfills
  {
    // Logical list of things we would normally need
    test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
    // Modernizr.load loads css and javascript by default
    nope : ['presentational-polyfill.js', 'presentational.css']
  },
  // Functional polyfills
  {
    // This just has to be truthy
    test : Modernizr.websockets && window.JSON,
    // socket-io.js and json2.js
    nope : 'functional-polyfills.js',
    // You can also give arrays of resources to load.
    both : [ 'app.js', 'extra.js' ],
    complete : function () {
      // Run this after everything in this group has downloaded
      // and executed, as well everything in all previous groups
      myApp.init();
    }
  },
  // Run your analytics after you've already kicked off all the rest
  // of your app.
  'post-analytics.js'
]);

Note the bottom line re: posting analyics. I dont want a new js file as that is another HTTP request however.

Shall I just keep this outside of yepnope? Is there any advantages to putting it within yepnope framework?

Adi


Source: (StackOverflow)

using yep/nope with document.ready

I am using yepnope.js but having a slight issue with on load loading a function

in the head i include yep nope and make a call to the relevant js file

<script type="text/javascript" src="/code/trunk/javascript/external/modernizr/modernizr-development.js"></script>

<script type="text/javascript" src="/code/trunk/javascript/external/yepnope.1.5.3-min.js"></script>

<script type="text/javascript">
yepnope({
  test: Modernizr.mq('only all and (max-width: 700px)'),
  yep: ['/templates/client/jquery/qff/plugin.mobile.js'],
  nope:['/templates/client/jquery/qff/plugin.website.js']
});    
</script>

and then at the bottom of the page

<script type="text/javascript">
jQuery(document).ready(function() 
{
    jQuery("#mainContent").setupQantas({
        startSlide: 1, 
        googleAnalytics:1,
        googleCode:""
    });
});
</script>

so i am looking at this on a main screen. so it's suppoed to call in plugin.mobile.js

in the plugin.mobile.js file

(function( $ ){

  $.fn.setupQantas = function( options ) {  

    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
        startSlide: 1, 
        googleAnalytics:0, // 1 sends to google
        googleCode: ""
    }, options);

    var methods = {};

    return this.each(function() {        

        if (settings.startSlide === 1) {
            alert("slide = 1");     
        } else {
            alert("slide > 1");
        }
    });
  };
})( jQuery );// JavaScript Document 

instead of giving the alert slide 1 it has the error

jQuery("#mainContent").setupQantas is not a function

if i dont use yepnope and just have it in a script tag it works. There seems to be a delay on when the yepnope loads in the js file and doesnt seem to do before doc.ready

is there a way around this?

thanks


Source: (StackOverflow)

Using modernizr.js / yepnope.js to load Google Maps API

Does anybody have any working code that allows one to use modernizr.load or yepnope to load the Google Maps API?

I am able to load JQuery & GMap3 using modernizr, however Google Maps API doesn't work unless I make a traditional script tag.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Please help me load Google Maps API with modernizr!</title>
    <style>
        #map { width: 500px; height: 300px; }
    </style>
    <script src="/js/modernizr-2.6.2.min.js"></script>
</head>

<body>
    <h1>Please help me load Google Maps API with modernizr!</h1>

    <div id="map">
        Placeholder
    </div>

    <script>
        function pageInit() {
            $("#map").gmap3({
                map:{
                    options: {
                        center: [18.01714, -76.750113],
                        zoom: 15,
                        mapTypeId: google.maps.MapTypeId.TERRAIN,
                    }
                }
            });
        }
    </script>


    <!-- I WANT TO REMOVE THE SCRIPT TAG BELOW AND REPLACE WITH MODERNIZR LOAD! -->
    <script src="//maps.google.com/maps/api/js?sensor=false&amp;language=en"></script>
    <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -->


    <script>
        Modernizr.load([{load: [
            '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
            '/js/gmap.jquery-5.1.1.min.js',
        ],complete: function () {loaded();}},]);

        function loaded() {
            $(document).ready(function() {
                pageInit();
            });
        }
    </script>
</body>
</html>

Well logic tells me I should do the following change after removing the script tag:-

Modernizr.load([{load: [
    '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
    '//maps.google.com/maps/api/js?sensor=false&amp;language=en',
    '/js/gmap.jquery-5.1.1.min.js',

But if I do this change the map doesn't load and I now get this error in the Javascript console:-

Load denied by X-Frame-Options: http://maps.google.com/maps/api/js?sensor=false&amp;language=en does not permit cross-origin framing.

Source: (StackOverflow)

"ERR! not a package" when installing node.js dependencies for yepnope.js

Pretty sure I'm doing something daft here - I'm not convinced it's specific to yepnope... my node knowledge isn't that hot.

Just trying to grab & build the repo to play around with some stuff (I'm not trying to use it on another project here), which I'm doing like this:

$ npm cache clean
$ git clone https://github.com/SlexAxton/yepnope.js.git
$ cd yepnope.js
$ git checkout v2.0     # this is the branch I want
$ npm install

But half way through the process I get something like this:

npm http GET https://registry.npmjs.org/nopt/-/nopt-2.1.1.tgz
npm http 200 https://registry.npmjs.org/wd/0.0.26
npm http GET https://registry.npmjs.org/wd/-/wd-0.0.26.tgz
npm ERR! not a package /var/folders/00/17q10000h01000cxqpysvccm004yw4/T/npm-13923/1363859875320-0.8848134819418192/tmp.tgz
npm http 304 https://registry.npmjs.org/uglify-js
npm ERR! Error: ENOENT, open '/var/folders/00/17q10000h01000cxqpysvccm004yw4/T/npm-13923/1363859875320-0.8848134819418192/package/package.json'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Darwin 12.2.1
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /Users/<username>/code/yepnope.js
npm ERR! node -v v0.8.12
npm ERR! npm -v 1.2.14
npm ERR! path /var/folders/00/17q10000h01000cxqpysvccm004yw4/T/npm-13923/1363859875320-0.8848134819418192/package/package.json
npm ERR! code ENOENT
npm ERR! errno 34

It still continues to the end, but ends with:

Extracting zip contents
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/<username>/code/yepnope.js/npm-debug.log
npm ERR! not ok code 0

The odd thing is, the npm ERR! not a package line occurs at a different place every time I try it (fresh repo clone every time) — maybe that's just because it fetches things asynchronously though?

I had a look at npm-debug.log and couldn't find anything too telling near the mentions of the path which is supposedly "not a package" - didn't really want to post the full file on here, but I'm happy to share chunks if someone can suggest what to look for.

Any ideas what's causing this to fail? Big thanks in advance!


Source: (StackOverflow)

Responsive design script handling using yepnope

At the footer of my responsive site I have tried to load different scripts for mobile and desktop using yep-nope and underscrore.js

var $window = $(window)
,throttled = _.throttle( packageLoader, 500);
$window.resize( throttled );

When the browser window is resized, the above function is triggered. It waits 500ms then fires off the "packageLoader function.

<script src="/assets/javascripts/yepnope.1.5.4-min.js"></script>
<script src="/assets/javascripts/underscore-min.js"></script>

function packageLoader(){

    Modernizr.load([
        {
            test: Modernizr.mq('(max-width:768px)'),
            yep: 
            [
                '/assets/javascripts/zepto.min.js',
                '/assets/javascripts/common-portable.js'
            ],
            nope:
            [
                '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
                // Accommodation guide plugins
                '/assets/javascripts/jquery.nouislider.min.js',
                '/assets/javascripts/jquery.cycle2.min.js',
                // END Accommodation guide plugins
                '/assets/javascripts/common-desktop.js'
            ],
            both: 
            [
                '/assets/javascripts/main.js'
            ]
        }
    ]);
}

window.onload = packageLoader();

The Problem:

IE7 +

I need a good solution to manage scripts that are running at different window sizes - I want the mobile site to be as light as possible. SO I believe that I need a way of.

• loading jQuery either from the cache or the file if not present. • loading zepto if user is viewing with a mobile • handling scripts

The above script may not be the best solution, if you have built a site that requires this control before let me know what libraries you have used please..

Much appreciation in advance


Source: (StackOverflow)

Using Drupal.settings.basePath in Modernizer / yepnope.js loads

I am currently starting development of drupal sites on Acquia. Using git and working locally is a new workflow for me. When building locally and trying to utilize Modernizr load / yepnope, my JS in my script.js file typically looks like this..

Modernizr.load([
    {
    test: Modernizr.mq('only all'),
    nope: '/sitename/docroot/sites/all/themes/theme/js/libs/polyfill.js'
    },
    ....

So that works locally on my machine, but when I commit my changes and push to my acquia development server the file path for the loaded scripts is incorrect, since it's not the same setup I guess.

http://mysite.devcloud.acquia-sites.com/mysite/docroot/sites/all/themes/theme/js/libs/polyfill.js

It needs to be the below, without the mysite/docroot in the URL.

http://mysite.devcloud.acquia-sites.com/sites/all/themes/theme/js/libs/polyfill.js

So that brings me to Drupal.settings.basePath. If I print this out it gives me /mysite/docroot/ on my local setup. If I do it on the dev server, it would print out something different (probably just / ).

So me being the amateur assumed I could do something like this.. (forgive the poor sample, I know it can be done better)

var myroot = Drupal.settings.basePath

Modernizr.load([
{
test: Modernizr.mq('only all'),
nope: myroot + 'sites/all/themes/theme/js/libs/polyfill.js'
},
....

And this of course does not work. Just returns query1 is not defined.

So I am sure there are faults in many of my attempts to make this work.. so if anyone can suggest something to me, either workflow related or how to fix my setup / code, that would be great.

Thanks


Source: (StackOverflow)

Modernizr.load (yepnope.js) IE conditional confusion

In the following code dd_belatedpng.js is loading despite the fact that I'm using Firefox 4.0.1. According to the yepnope.js documentation, the ielt7! prefix should cause the script only to load if the browser is IE less than version 7. Is this functionality removed from the Modernizr.load implementation (I believed that one was just an alias for the other), or a bug, or, as I suspect, me just missing/misunderstanding something obvious? Thanks for your help. Here's the code.

Modernizr.load([
    {   
        load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
        complete: function() {
            if(!window.jQuery) {
                Modernizr.load('/inc/jquery-1.6.1.min.js');
            }   
        }   
    },  
    {   
        load : 'ielt7!/inc/dd_belatedpng.js',
        callback: function() {
            $(function() {
                DD_belatedPNG.fix("img, .png_bg");
            }); 
        }   
    }/*,
    'jquery.plugins.js',
    'my.scripts.js'*/
]);

Source: (StackOverflow)

Modernizr - Which scripts get loaded asyncronously?

I have the following:

Modernizr.load([
{
  load : '//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js',
  complete : function () {
    if ( !window.jQuery ){
      Modernizr.load('/js/jquery-1.6.2.min.js');
    }
  }
},
{
  load : ["/js/someplugin.js", "/js/anotherplugin.js"],
  complete : function()
  {
    // do some stuff
  }
},
{
    load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
}
]};

I read that Modernizr loads scripts Asyncronously. But in the above example, which ones are loaded async?

Do all of the following get loaded asyncronously?

  1. jquery.min.js
  2. someplugin.js
  3. anotherplugin.js
  4. ga.js

Or is it a combination of async and ordered loading like this:

  1. jquery.min.js is loaded first
  2. Then someplugin.js and anotherplugin.js is loaded async
  3. finally, ga.js is loaded

I'm having a hard time testing which case it is.


Source: (StackOverflow)

jquery yepnope throws an error when loading the same file twice

                $("#register").click(function()
                {
                     yepnope({
                          load: ['js/join.js', 'css/join.css',  'css/join_form.css'],
                     });

                     $('#midcol').load('join.htm');             
                });

When the register link is clicked yepnope loads those files listed as expected. When the register link is clicked a second, third, fourth etc... time yepnope throws the following error:
Could not convert JavaScript argument arg 0 [nsIDOMHTMLHeadElement.insertBefore] js/yepnope/yepnope.js Line 248

I was under the impression that yepnope will only load the file if it does not exist? Am I required to run a check on every file that I want to load with yepnope? That will seem a bit daunting if that is the case.

I could not find a solution to my issue while searching the web for HOURS. I did however, come across CURL.js. It has a rather smaller footprint. I was able to load my dependencies without any issues. Below is an example of code to load dependencies.

var cnf = {
     baseUrl: 'scripts',
     pluginPath: 'curl/plugin',
     paths: {
          curl: 'curl/src/curl',
     },
};

curl(cnf, ['js!join.js!order', 'domReady!'], function () {
     $("#register").click(function(){
          $("#midcol").load("join.htm");    
     });
});

Source: (StackOverflow)

Javascript array manipulation: Is there a better way to do the following?

I have the following code which does:

  1. Grabs text from an element on the page
  2. Filters for the particular element
  3. Splits on the '\n'
  4. Removes all elements of the array that are white space

This seems to take a little more time than I'd like and doesn't remove all the whitespace filled elements of the array, as you might expect.

Just for reference I then combine the two arrays into one and load the scripts and styles using YepNope. This process takes about 1.5s which is really long for the user to wait.

How can I improve the speed of this?

var $containerHtml = $(html);

    // Add the scripts
    scriptArray = $.grep($containerHtml.filter('#includeScripts').text().split('\n'), function (element, index) {
                    return element !== "" && element !== " ";
                });
    // Add the styles
    styleArray = $.grep($containerHtml.filter('#includeStylesheets').text().split('\n'), function (element, index) {
                    return element !== "" && element !== " ";
                });

    // Combine the two arrays into 1
    combinedArrays = scriptArray.concat(styleArray);

    // Load the scripts and styles 
    yepnope([{
        load: combinedArrays,
        callback: function (url, result, key) {
                if (window.console && window.console.firebug) {
                    console.log("Loaded " + url);
                }
        }}]);

Source: (StackOverflow)