How can I present a different next/Image based on the user's preferred color scheme? - image

I'm trying to use a next/image instead of a regular img tag in the code below. With the regular <img> tag, the following achieves exactly what I'm looking for:
<div>
<picture>
<source
srcSet="https://via.placeholder.com/100/333333/ffffff.png"
media="(prefers-color-scheme: dark)"
/>
<img
src='https://via.placeholder.com/100/dddddd/000000.png'
width='100px'
height='100px'
alt='Placeholder image'
/>
</picture>
<p>Change your OS or browser's preferred color scheme to see a different image.</p>
</div>
Indeed, when I set my OS (or browser) to the dark theme, I get a dark image, and vice-versa for the light theme.
However, if I try the same thing with a next/image, I just get the light-themed image every time… I can't put this into a snippet because next/image requires a Next.js server, but here is the code that I'm using, which, in my tests, is backed by a Next.js development server with the appropriate image-related settings configured in next.config.js:
// pages/test.js
import Image from 'next/image'
export default function MyWebPage () {
return (
<div>
<picture>
<source
srcSet="https://via.placeholder.com/100/333333/ffffff.png"
media="(prefers-color-scheme: dark)"
/>
<Image src='https://via.placeholder.com/100/dddddd/000000.png' width='100px' height='100px' alt='Placeholder image' />
</picture>
<p>You can change your OS or browser's preferred color scheme, but you'll always see the light-theme image.</p>
</div>
)
}
Here I never get the dark-themed image, unfortunately.
Theories:
Perhaps next/image doesn't interact with the <picture> tag exactly the same way as <img>? But I'm not finding anything online about using next/image with the <picture> tag…
Perhaps I should be providing this media-query-dependant source set in a different way when using next/image? But, I'm not finding any media attribute in the next/image docs…
Question:
How can I change the src of my next/image based on the user's preferred color scheme?
Non-solutions:
I could put 2 images on the page and use display: none on one of the two as a function of the user's preferred color scheme, but I'm hoping to find a solution that doesn't require so many duplicate images all over the place, which incurs a (small) performance penalty and makes the code that much harder to maintain, or that much more complex if a helper component is created.
I could change the src using Javascript when the page loads, but this would result in a flash of incorrectly styled content and generally does against my objective of having my page fully server-rendered and compatible with browsers where Javascript is turned off.
I could use cookies to let the server know about a user's color scheme preference and render the page consequently, but this would not work for the very first visit and comes with the requirement to include a cookie bar to inform the user of the reasons behind the use of cookies, as well as a way to opt-out.

Related

Where to put images with SvelteKit

I have been using Svelte for a little while and now I have switched to SvelteKit so I can add multiple pages. I want to add some images to my site but I don't know where to put them. In Svelte I would just put them in public/images but there is no public folder with SvelteKit (I set it up with npm init svelte#next my-app if that matters). Would I put them in static?
Thanks!
I added the images in static/images and referenced them with src="/images/photo.jpg" like #b2m9 said and it works perfectly.
I recommend putting images under src/lib, not static. For example you could make a src/lib/images or src/lib/assets folder and put them there.
The reason is performance:
For files imported from anywhere under src, at compile time Vite adds a hash to the filename. myImage.png might end up as myImage-a89cfcb3.png. The hash is based on the image contents. So if you change the image, it gets a new hash. This enables the server to send a very long cache expiration to the browser, so the browser can cache it forever or until it changes. It's key-based cache expiration, which IMO is the best kind: cached exactly as long as it needs to be. (Whether the server actually sends the right caching headers in the response may depend on which SvelteKit adapter you use and what host you're on.)
By contrast, images under static don't have a hash added to their name. You can use the static directory for things like robots.txt that need to have a specific filename. Since the filename stays unchanged even if its contents change these files by necessity end up having a cache-control value that includes max-age=0, must-revalidate and an etag, which means even if the browser caches the image it still has to make a server round-trip to validate that the cached image is correct. This slows down every image on your site.
Usage:
When putting images under src/lib, you reference them like this:
<script>
import img from '$lib/images/img.png';
</script>
<img src={img} alt="Image" />
I recommend simplifying by adding svelte-preprocess-import-assets to your project, which automates the process of importing images and cleans up your code. You wrote the following and it generates the code above:
<img src="$lib/images/img.png" alt="Image" />
As Sveltekit uses Vitejs, there is a easy solution mentioned in Vitejs official web site (Click Here).
First inside the script tag :
<script>
const imgUrl = new URL('./img.png', import.meta.url).href
</script>
then inside your Image tag just use that variable,
<img src="{imgUrl}" alt="" />
or,
<div class=" h-screen w-full" style="background-image: url('{bgUrl}') ;">
</div>
You can import static images from any relative path.
there is also svelte-image.
"Svelte image is a pre-processor which automates image optimization using sharp.
It parses your img tags, optimizes or inlines them and replaces src accordingly. (External images are not optimized.)
Image component enables lazyloading and serving multiple sizes via srcset.
This package is heavily inspired by gatsby image.
Kudos to #jkdoshi for great video tutorial to Svelte Image."
-https://github.com/matyunya/svelte-image

Linking to image from cutom component in VuePress

I want to display an image in my VuePress markdown file. Normally, I'd go with:
![My Image](./resources/myimg.png)
However, I'd like to create a custom Vue component that will style the images in a specific way. Then, some images would be displayed using the "standard" markdown syntax (like above), and some others using my custom component.
With my custom component, I'd display the images like this:
<MyComponent src="./resources/myimg.png"/>
As you can see, the images are placed alongside my markdowns, in a resources directory. This makes sense for me, because the image is close to the markdown where it gets displayed.
Unfortunately, the image does not get displayed when I use MyComponent. VuePress (webpack?) handles the images during build and places them in some other directory with a different name. The "standard" Markdown image reference works fine, its URL to the image is set up correctly by VuePress. However, MyComponent does not work, because the src parameter is just a string for VuePress and it does not transform it in any way.
I know that one solution would be to place my images in the /vuepress/public folder. However, I would want to keep the same organization as I have now - images alongside documents.
How can I achieve that?
I had the same issue.
I used the answer #papey provides for a Vue question here
Here is one thing he suggests
<template>
<div id="app">
<img :src="require('./assets/logo.png')"/>
</div>
</template>
<script>
export default {
}
</script>
<style lang="css">
</style>

Can the CKEditor show some html while saving it as something else?

I'd like to adapt my CKEditor so that when editing an image or other object it will show something like this in the editor view
<figure style="float: left">
<img src="sample.jpg" />
<figcaption>Caption</figcaption>
</figure>
On save it should transform this part to something else, for example
<node id=3 />
Does the CKEditor have any support for this, maybe through Widget, dataProcessor, or otherwise?
The short answer - yes, this can be done using the CKEDITOR.dataProcessor.
First thing to notice is that if you would use the widgets system (you will be interested in the image2 plugin), then you would be able to use downcasting to transform captioned images into whatever you want. Similar thing is done in Drupal 8, because Drupal saves captioned images as <img src=".." data-caption=".." ..>. (Note: Drupal 8 uses the image2 plugin but it overrides some things like e.g. downcasting method.)
The relation between mentioned CKEDITOR.dataProcessor and the widgets system is that the widget system uses the data processor to perform upcasting and downcasting of the widgets. Upcasting means discovering elements that should be turn into widgets and performing necessary transformations on the loaded data. Downcasting is the opposite.
You can also use the data processor without using widgets. You can do that:
either by using the filter.addRules() method on the editor.dataProcessor.htmlFilter and editor.dataProcessor.dataFilter filters,
or by hooking into the data processing on higher level using the editor.toDataFormat and editor.toHtml events.

Can you control pinterest's "find image" results?

Rather than add Pin It buttons through our site, I would like to simply control what images show up in Pinterest's "Find Image" results if a user decides to pin one of our URLs.
As of now, "Find Images" allows the user to scroll through the images it finds on the page so they can select which image to pin. The "found" images start with the first jpg in the html file, I'm assuming (could that be a bad assumption??). On our site, this forces a user to scroll through about 15 navigation and promotion images before arriving at the featured product image. Is there any way to specify this image to show first in those results? Maybe through a meta tag, or by adding a class or id to the element?
Without a public Pinterest API, this seems like just guesswork, but I wanted to see if anyone else has run into this, or solved this. Thanks.
A lot of search results including the Pinterest Help Center talk about using nopin in HTML elements, which is invalid HTML. What they don't document is a data attribute to the same (well formed) effect.
<img src="foobar" data-pin-nopin="true" />
Adding the nopin attribute will exclude the image from appearing on Pinterest:
<img src="..." nopin>
I solved this by simply loading the image before all others in the page. In this case, I gave it width="0" and height="0" (you could also give it style="position: absolute; left: -9999px; top: 0;" just to be sure).
This won't break the page layout, but will force Pinterest to find this image first. The only downside is that the browser will load the page a few milliseconds slower, but if you're reusing this image later in the page anyway, you should make up for lost time then.
Pinterest will find any images from <img> tags (it will ignore CSS background images) that are at least 80px x 80px.
The order the images show up on in the Pinterest list is determined by the order they are specified in the HTML.
As you have discovered, you can alter the CSS of an image to "hide it" without actually hiding it by either moving it off the page with absolute positioning or 0 height and width. Any images that are set to display: none will not be picked up by Pinterest.
You can instruct the share preview to only grab specific images from the page by using the “image_include” configuration option. First, set image_include to your desired class name (id selectors are not allowed, only class selectors), then add that same class name to each of the images on the page that should be grabbed. For image_include, don’t add the ‘.’ selector. Here’s an example:
<script type="text/javascript">
var addthis_config = {
image_include: "at_include"
}
</script>
Once image_include has been defined with a class, add that class to the desired images on the page. In this example, the only images on the page that will be grabbed, will be the images with the at_include class (img1.jpg and img3.jpg).
<img src="http://www.example.com/img1.jpg" class="at_include" />
<img src="http://www.example.com/img2.jpg" />
<img src="http://www.example.com/img3.jpg" class="at_include" />
I was reading this blog which suggests the following:
Use the global no pin flag to prevent pinning on the whole site
Manually add the Pin It widget to those images you want to make pin-able.
Given Pinterest's webmaster tools appear to only have a blacklist, rather than a whitelist option (that you are seeking), this could be a possible solution. Another stated benefit of this is you can also supply suggested pin text through the Pin It widget.
Only downside to this I guess is that it may break the user's own Pin tools. Pinterest does allow you to supply a custom "denied" message, so I guess you can say "please use our site's pin buttons directly".
I've tried this, and it works. It seems like a decent approach, at least until Pinterest sees fit to add some better tools, such as an image whitelist option. The main drawback is needing to add Pin-it buttons on every image you want to enable for your users & your users may be annoyed that they can't pin anything.
Unfortunately, there is no way to mark several images on your page as preferred, but you can mark one image to stay at the top of your images when someone pin it. Specify this meta-tag in <head>:
<meta property="og:image" content="http://YOUR-DOMAIN.com/IMAGE.jpg"/>
I have not found official confirmation for this feature, but it works great with addthis sharing plugin.
Add this script before the actual call to pinterest. And set images that you do not want to show with a class called 'nopin'
<script type="text/javascript">
var addthis_config =
{
image_exclude:'nopin'
}
</script>
<div id="toolbox" class="addthis_toolbox addthis_default_style">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_button_tumblr"></a>
<a class="addthis_button_pinterest"></a>
</div>
</div>
If anyone is using AddThis, please check this thread: http://support.addthis.com/customer/portal/questions/1570789
AddThis has some, uh, unique functionality that affects the image picker presented. As in, when there is only one image on the page, it ignores the defined og:image.
If you set that lone image to be excluded, then the image picker won't show any images for selection.

Show a custom image for some images if image not found - Lighttpd

I have a site that creates images for some bit of content after the content is created. I'm trying to figure out what to do in between the time the content is created and the image is created. My thought is that I might be able to set a custom image to display on a 404 error on the original image. However, I'm not sure how to do this with lighttpd. Any ideas or alternatives?
EDIT: The issue is the user isn't the one creating the content, it's being created by a process. Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider. However, I don't want a slow server on the provider end to slow down the addition of new products. So a separate process goes through and creates the image later, where available. I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.
Another alternative on the client side is to do:
<img src="/images/generated_image_xyz.png"
onerror="this.src='/images/default_image.png'; this.title='Loading...';" />
Use the <object> tag in HTML with a fallback to the default image.
<P> <!-- First, try the Python applet -->
<OBJECT title="The Earth as seen from space"
classid="http://www.observer.mars/TheEarth.py">
<!-- Else, try the MPEG video -->
<OBJECT data="TheEarth.mpeg" type="application/mpeg">
<!-- Else, try the GIF image -->
<OBJECT data="TheEarth.gif" type="image/gif">
<!-- Else render the text -->
The <STRONG>Earth</STRONG> as seen from space.
</OBJECT>
</OBJECT>
</OBJECT>
</P>
(Example from w3.org)
As I understand your problem: You want to show an intermediate image until the real image has been generated?
You could display a loading image and use AJAX to change that DOM node into the real image when it's been created. You could write it from scratch or use any of the well known and stable AJAX libraries out there, if you have no preference of your own take a look at jQuery.
Further to #kentlarsson - if you want to do it via Javascript, I recently found this code:
http://jquery.com/plugins/project/Preload and the demo at http://demos.flesler.com/jquery/preload/placeholder/ which does as he suggests - with its 'notFound' option.
I don't know enough about lighttpd to tell you about setting up a custom image with one or more subdirectories in a site though.
I think you could probably solve this on the client side alone.
Based on Jaspers' answer, you could do:
<OBJECT data="/images/generated_image_xyz.png" type="image/png">
Loading..<blink>.</blink>
</OBJECT>
Also layering backgrounds using CSS you could do:
<style type="text/css">
.content_image { width:100px; height: 100px;
background: transparent url('/images/default_image.png') no-repeat }
.content_image div { width:100px; height: 100px; }
</style>
<div class="content_image">
<div style="background:
transparent url('/images/generated_image_xyz.png') no-repeat" />
</div>
The latter solution assumes you don't have any transparency in your generated image.

Resources