Coder Social home page Coder Social logo

stephanmax / grunt-responsive-images-extender Goto Github PK

View Code? Open in Web Editor NEW
239.0 239.0 20.0 81 KB

A Grunt plugin that extends HTML image tags with srcset and sizes attributes.

Home Page: https://www.npmjs.com/package/grunt-responsive-images-extender

License: MIT License

JavaScript 55.08% HTML 44.92%

grunt-responsive-images-extender's People

Contributors

smaxtastic avatar sprrw avatar stephanmax 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

grunt-responsive-images-extender's Issues

Add ability to apply srcset conditionally based on selector

Currently a srcset is applied to every image tag (except those with a pre-existing srcset). This might affect image tags you'd prefer to leave alone. I've added an optional options.selector which, if defined, will only apply to matching tags.

--- responsive_images_extender.js.orig  2015-10-05 15:04:15.250587100 -0700
+++ responsive_images_extender.js       2015-10-07 15:06:42.355054900 -0700
@@ -93,7 +93,7 @@
           grunt.log.verbose.ok('Detected width attribute for ' + filePath + fileExt + ' (not responsive, but retina-ready)');
         }
         else {
-          if (!hasSrcset) {
+          if (!hasSrcset && (options.selector === undefined || image.is(options.selector))) {
             image.attr('srcset', buildAttributeList(options.srcset, buildSrc));
             grunt.log.verbose.ok('Extend ' + filePath + fileExt + ' with srcset attribute');
           }

Affects html output

It seems that plugin affects html output far beyond just adding srcsets.

For instance, it changes HTML quotes:

<div class='test'></div>

to

<div class="test"></div>

Also, it affects inner whitespacing:

<div               class="test"></div>

becomes

<div class="test"></div>

While issue with whitespace doesn't seem to be serious (though, it make Git comparison show a lot of unintended changes), changes of quotes actually is a serious issue, because it will break following case:

<div data-settings='{"id":9089}'></div>

Result will be

<div data-settings="{"id":9089}"></div>

which effectively makes HTML wrong.

Removes self closing forward slashes from inline SVG path elements

Hi,

This plugin works like a dream, except that it strips self closing forward slashes from inline SVG path elements in inline SVGs:

<path d="..."/>

becomes

<path d="...">

And that breaks the inline SVGs that I have on my site (that have more than one path), unfortunately. I tried ignoring the <svg> and <path> elements via the ignore option, but to no avail. I also tried explicitly closing the paths:

<path d="..."></path>

But those got mangled too.

Any idea what’s happening? Here’s a link to how I’ve configured the plugin in my Gruntfile, if that’s any help. I’ve commented out the task itself for the time being.

Path must be a string

Hi

I'm receiving following error:

Warning: Path must be a string. Received [ 'build/blog/2015-10-12-example-article/index.html' ] Use --force to continue.

Here is my config

module.exports = ->
  @config 'responsive_images_extender',
    thumbnails:
      files: [
        expand: true
        cwd: 'build/'
        src: ['**/*.{html,htm,php}']
        dest: 'test/'
      ]

It's quite same, as the one in readme.md.

Versions:

grunt-cli v0.1.13
grunt v1.0.1
node v6.2.0

Here is full log with message:

conemu_2016-08-04_22-36-52

Am I missing something obvious?

Using srcsetRetina option only

Is it possible to use the plugin for just generating srcsets with @2x versions? I can't make neither "non-responsive.png" example from docs, nor the code below to work. It generates default size srcsets, as if the options were empty:

Edit: Figured out that in order to make Retina work, width attribute should be specified. Any workaround to make it work without an attribute?

responsive_images_extender: {
  complete: {
    options: {
      srcsetRetina: [{
        suffix: '@2x',
        value: '2x'
      }]
    },
    files: [{
      expand: true,
      src: ['index.html'],
      cwd: '',
      dest: 'build/'
    }]
  }
}

http and https issue

Hi @stephanmax!

Following html:

<img src='https://placekitten.com/100/100'>

will throw an error:

chrome_2017-06-22_22-11-55

It seems that plugin doesn't ignore remote files.

Option to not include "src" attribute

So the original image doesn't get downloaded before the picturefill starts doing it's thing.
In a project I'm working on, the original image is also the biggest one, thus the issue. Or am I doing something wrongly?

Seems to require src files to be in src directory, regardless of cwd or baseDir

Using a directory structure like this

.Gruntfile.js
src
dest
tmp

I could not get this plugin to work. I kept getting errors from grunt on the command line such as

Warning: ENOENT: no such file or directory, scandir '' Use --force to continue.

or

Warning: ENOENT: no such file or directory, scandir '/2008/site/images' Use --force to continue.

Don't ask me here /2008/site/images is because it's a mystery. Nothing to do with my site, my computer nor my images or folder structure. Ghost in the machine.

If I gave the plugin some impossible baseDir or cwd like "sadfasdfasgdafdsfasf" it would complete without error. However if I gave it /tmp/ or /temp/ or /build/ (all of which existed), I'd get an error.

If I gave the plugin /src/ things would work fine. However, I cannot do that in my configuration because I have a pre-bake step.

To solve the issue, I had to but /tmp/ inside /src/

        responsive_images_extender: {
            target: {
              options: {},
              files: [{
                expand: true,
                src: ['src/temp/**/*.{html,htm,php}'],
                cwd: '',
                flatten: true,
                dest: 'dest/'
              }]
            }
          },

Works fine. But not possible to have /src/ as a sibling to /src/ and /dist/. This is strange since all other Grunt plugins allow this and you have cwd and baseDir options that seem to allow this.

New Version 2.0 stops working with "Warning: Cannot read property 'charAt' of undefined Use --force to continue."

After doing a grunt responsive_images_extender -v it seem to me tracking image tags with svg file loaded, which leads to this error...
.
.
.
.
Reading build/templates/views/auth.register.html...OK
Writing build/templates/views/auth.register.html...OK
Reading build/templates/views/auth.signup.html...OK
Writing build/templates/views/auth.signup.html...OK
Reading build/templates/views/benefits.html...OK

Found only one file for /assets/images/welcome/icon_pdf.svg
Found only one file for /assets/images/welcome/icon_pdf.svg
Found only one file for /assets/images/welcome/icon_pdf.svg
Found only one file for /assets/images/4_efficient.svg
Warning: Cannot read property 'charAt' of undefined Use --force to continue.

Further investigations on how to properly add svg to html brought this as alternative approach:

<object data="your.svg" type="image/svg+xml">

</object>

But this approach did not work here, because this line:

    <object data="/assets/images/logo_LambdaNow.svg" type="image/svg+xml" title="LambdaNow" border="0" class="logo"></object>

was completely messed up, after your algorithm went over my code (please see:

        <object data=" assets="" images="" logo_lambdanow.svg"="" type="image/svg+xml" title="LambdaNow" border="0" class="logo">
      </object data="></a>

This lead to the next problem, that my html2js task was running forever without doing anything further and telling about anything.

So at the moment I did not come up with any solution. Maybe you can help?

Another feature request would be, ignoring img tags with svg files.

Sizes array need some improvements

First, awesome grunt task! :)
One nit though - I was looking at the readme, and saw that there is a default array for sizes used when the user defines nothing. That makes little sense.

sizes, by its definition, is tied to the particular page's design. I would also say that a generic sizes value that would be applied to all of the page's images is not very helpful.

Maybe it'd be better to define sizes as an array per selector, so that users can define sizes for their hero image, a different one for article images, etc.
If a certain image has no sizes array associated with it, it's better to leave sizes out, and let the browser use the default 100vw.

WDYT?

No srcset

I'm running into issues with the Grunt responsive_images_extender.

None of my srcset are set up in the build folder.

According to the readme documentation, it says that the default task code will set up the srcset directly from the image sizes created from the first responsive_images task. (which in my scenario adds 3img sizes in the build folder)

Although when I run it through the terminal with the following default config code:

grunt.initConfig({
  responsive_images_extender: {
    target: {
      options: {},
      files: [{
        expand: true,
        src: ['**/*.{html,htm,php}'],
        cwd: 'src/',
        dest: 'build/'
      }]
    }
  }

});

it doesn't work. I know that the html files do get processed as they show up in the build folder when I run the task. The terminal output also tells me they have been processed:

Running "responsive_images_extender:target" (responsive_images_extender) task
>> Processed 157 <img> tags

Am I misinterpreting the documentation and still need to do more configuring? Any feedback will be greatly appreciated.

Invalid urls on win32/64 systems

Node on windows has path.sep set to '\'. This causes "urls" created with path.join() to be invalid. The fix is to use path.join() only for file/path manipulation, and url.resolve() for creating urls. I can confirm that this patch for buildSrcset() works, but my code doesn't exercise setSrcAttribute(). (All nodeunit tests fail on windows systems.)

--- tasks/responsive_images_extender.js 2016-06-05 08:36:50.673658300 -0700
+++ tasks/responsive_images_extender.js 2016-06-09 11:45:06.480446700 -0700
@@ -16,6 +16,7 @@

   var fs = require('fs');
   var path = require('path');
+  var url = require('url');
   var cheerio = require('cheerio');
   var sizeOf = require('image-size');

@@ -74,7 +75,9 @@
           var candidate;

           for (var img in srcMap) {
-            candidate = path.join(path.dirname(imgSrc), img);
+            // path.join() creates invalid urls on systems where path.sep = '\\'
+            // candidate = path.join(path.dirname(imgSrc), img);
+            candidate = url.resolve(imgSrc, img);
             if (width !== undefined) {
               candidate += ' ' + Math.round(srcMap[img] / width * 100) / 100 + 'x';
             }
@@ -118,7 +121,9 @@
               }).reduce(function(a, b) {
                 return b[1] < a[1] ? b : a;
               });
-              imgElem.attr('src', path.join(path.dirname(imgSrc), smallestImage[0]));
+              // path.join() creates invalid urls on systems where path.sep = '\\'
+              // imgElem.attr('src', path.join(path.dirname(imgSrc), smallestImage[0]));
+              imgElem.attr('src', url.resolve(imgSrc, smallestImage[0]));
               break;
             default:
           }

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.