How to preload css files without applying them with yepnope.js?

876 Views Asked by At

I have implemented a stylesheet switch solution where the stylesheet href is changed on click with jQuery.

It is working fine but on the first page load, there is a flicker when changing between stylesheets because the different css files haven't been loaded before (once they have been used there is no flicker).

So I am using yepnope.js to preload the css files with:

yepnope([{
  load: 'http://path/to/stylesheet_1.css',
  callback: function (url, result, key) {
    console.log(url, result, key);
  }
}, {
  load: 'http://path/to/stylesheet_2.css',
  callback: function (url, result, key) {
    console.log(url, result, key);
  }
}]);

And everything is working as expected except that each stylesheet is being applied when it is loaded.

Is there anyway to preload the stylesheets without actually applying them?

Edit

I also tried:

yepnope([{
  load: 'preload!http://path/to/stylesheet_1.css'
}, {
  load: 'preload!http://path/to/stylesheet_2.css'
}]);

after reading about preload! Prefix on their documentation page but that didn't seem to work.

Edit 2

Also tried adding:

yepnope.addFilter(function (resourceObj) {
  resourceObj.noexec = true;

  return resourceObj;
});

But it didn't seem to have an effect.

2

There are 2 best solutions below

0
On

you could ajax request the css file, and cache the text content of it, and later stick it into a style tag when you wanted to load it.

0
On

If you re-define the 'preload' prefix before using that seems to work:

yepnope.addPrefix("preload", function(resource) {
  resource.noexec = true;
  return resource;
});

Source: https://gist.github.com/dzello/1015783