Giter Club home page Giter Club logo

head-plugin's Introduction

Swup Head Plugin

A swup plugin for updating the contents of the head tag.

  • Adds any meta tags and assets from the next page to the current document
  • Updates the lang attribute of the html element
  • Supports delaying the transition until new stylesheets have loaded

Installation

Install the plugin from npm and import it into your bundle.

npm install @swup/head-plugin
import SwupHeadPlugin from '@swup/head-plugin';

Or include the minified production file from a CDN:

<script src="https://unpkg.com/@swup/head-plugin@2"></script>

Usage

To run this plugin, include an instance in the swup options.

const swup = new Swup({
  plugins: [new SwupHeadPlugin()]
});

Markup

When using noscript tags inside the head, make sure they only contain the node types allowed inside the head element. Otherwise, the browser will implicitly close the head element and interpret them as part of the body, most probably breaking this plugin and leading to unforseen results. See the following issue for details and a fix.

Options

persistAssets

Whether to keep orphaned link, style and script tags from the old page that weren't included on the new page. Useful for third-party libraries that add custom styles but can only be run once.

Defaults to false, i.e. orphaned assets will be removed.

Setting it to true acts as a shortcut for setting the persistTags option to a selector of link[rel=stylesheet], script[src], style.

new SwupHeadPlugin({
  persistAssets: true
});

persistTags

Define which tags will be persisted when a new page is loaded.

Defaults to false, i.e. all orphaned tags will be removed.

new SwupHeadPlugin({
  // Keep all orphaned tags
  persistTags: true,

  // Keep all tags that match a CSS selector
  persistTags: 'style[data-keep-style]',

  // Use a function to determine whether to keep a tag
  persistTags: (tag) => tag.children.length > 1
});

awaitAssets

Setting this to true will delay the transition to the new page until all newly added assets have finished loading, imitating the standard browser behavior of render-blocking requests. Currently only supports stylesheets. Defaults to false.

new SwupHeadPlugin({
  awaitAssets: true
});

head-plugin's People

Contributors

daun avatar dependabot[bot] avatar gmrchk avatar hirasso avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

head-plugin's Issues

Swup gets stuck when replacing head

I want to replace canonical and hreflang links on each page, so I installed this plugin normally:

import SwupHeadPlugin from '@swup/head-plugin';
const swup = Swup(plugins: [new SwupHeadPlugin()]);

However, once it is installed and I navigate from the starting page to a new page, swup gets stuck on swup-enabled is-changing to-my-new-page is-rendering, and the page layout "breaks" (no css applied, scripts seem to work). No console errors.

The head is correctly replaced at first, however once it is stuck and layout "broken", neither content nor head are replaced anymore.

What could be the issue here? It can't have to do with another "transition" class (as was the case in another issue.) Thanks a lot for any help!

Safe to use this plugin?

I've been running into the common issue with <link rel="canonical" href="..." /> in the head. In the docs you mention that this plugin is "rather experimental". What exactly do you mean by this? Is it safe to use in production?

Also, does this plugin exchange the whole <head>? Can't we just change the canonical meta tags? Would that make this plugin "safer"?

Refresh head before swup containers ?

Hi,
When I use the head plugin the CSS is broken a few moment after the transition, and it's fix when the CSS file is load.

it's posible to refrech the head before swup containers ?

Thanks, and sorry for my bad english.

noscript tags prevent head contents from updating

Description of the issue

I want to add GA, Linkedin & Facebook Pixels tracking scripts in the head of my pages, it makes the styles disappears when I change the page, but not my JS from Astro. It also log replicated GA / FB / Linkedin tracking instance.

I tried to use the scripts-plugin with optin enabled but it doesn't solve the issue.

Is there something I'm doing wrong ? What should I do to make it work ?
I know there is a GA Plugin, but since I have also FB pixel & Linkedin Tracking I'd like a solution that can be replicable to these 2 other scripts.

How to reproduce the issue

It's the head of my astro project :

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<!-- Meta Pixel Code -->
		<script>
			!function(f,b,e,v,n,t,s)
			{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
			n.callMethod.apply(n,arguments):n.queue.push(arguments)};
			if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
			n.queue=[];t=b.createElement(e);t.async=!0;
			t.src=v;s=b.getElementsByTagName(e)[0];
			s.parentNode.insertBefore(t,s)}(window, document,'script',
			'https://connect.facebook.net/en_US/fbevents.js');
			fbq('init', 'blablabla');
			fbq('track', 'PageView');
		</script>
		<noscript><img height="1" width="1" style="display:none"
		src="https://www.facebook.com/tr?id=blablabla&ev=PageView&noscript=1"
		/></noscript>
		<!-- End Meta Pixel Code -->

		<!-- Google tag (gtag.js) -->
		<script async src="https://www.googletagmanager.com/gtag/js?id=G-blablabla"></script>
		<script>
			window.dataLayer = window.dataLayer || [];
			function gtag(){dataLayer.push(arguments);}
			gtag('js', new Date());

			gtag('config', 'G-blablabla');
		</script>

		<script type="text/javascript">
			_linkedin_partner_id = "blablabla";
			window._linkedin_data_partner_ids = window._linkedin_data_partner_ids || [];
			window._linkedin_data_partner_ids.push(_linkedin_partner_id);
		</script>
		<script type="text/javascript">
		(function(l) {
			if (!l){window.lintrk = function(a,b){window.lintrk.q.push([a,b])};
			window.lintrk.q=[]}
			var s = document.getElementsByTagName("script")[0];
			var b = document.createElement("script");
			b.type = "text/javascript";b.async = true;
			b.src = "https://snap.licdn.com/li.lms-analytics/insight.min.js";
			s.parentNode.insertBefore(b, s);})(window.lintrk);
		</script>
		<noscript>
			<img height="1" width="1" style="display:none;" alt="" src="https://px.ads.linkedin.com/collect/?pid=balblalba&fmt=gif" />
		</noscript>
		<SEO seo={props.seo} />
	</head>

Context and environment

    swup({
      theme: "overlay",
      containers: ['#transitionnable'],
      animationSelector: 'transition-',
      smoothScrolling: true,
      debug: process.env.WP_ENV === "development",
      preload: false,
      globalInstance: true,
      plugins: [new SwupScriptsPlugin({
        body: false,
        optin: true
      })]
    })

Make removal of tags optional

Some third-party libraries inject style tags into the head, Google Maps among others. Since those style tags aren't present on the next page, SwupHeadPlugin will remove them, breaking maps on subsequent pages.

Could the removal of tags in the head be optional? So it would still merge new tags, but not delete the old ones. Not sure if that's complicated or easy to do with the current implementation.

For what it's worth, that's exactly what turbolinks is doing and it seems to be working for most users: Styles get left in head?

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.