Concatenated all JS into a single file (#624)

no issue

- moved large inline JS from templates into separate JS files
  - floating header
  - gallery card support
- use `gulp-concat` to concatenate all JS files into a single `built/casper.js` file
- reduces external JS file requests from 3 (jquery, infinite-scroll.js, jquery.fitvids.js) down to 2 (jquery, casper.js) and reduces page size by removing repeated inline code
This commit is contained in:
Kevin Ansfield 2019-10-20 15:55:06 +02:00 committed by GitHub
parent 53ad2d8096
commit 978ffe0eb6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 165 additions and 94 deletions

2
assets/built/casper.js Normal file
View file

@ -0,0 +1,2 @@
!function(n){"use strict";n.fn.fitVids=function(e){var i={customSelector:null,ignore:null};if(!document.getElementById("fit-vids-style")){var t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("div");r.innerHTML='<p>x</p><style id="fit-vids-style">.fluid-width-video-container{flex-grow: 1;width:100%;}.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>',t.appendChild(r.childNodes[1])}return e&&n.extend(i,e),this.each(function(){var e=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"];i.customSelector&&e.push(i.customSelector);var r=".fitvidsignore";i.ignore&&(r=r+", "+i.ignore);var t=n(this).find(e.join(","));(t=(t=t.not("object object")).not(r)).each(function(){var e=n(this);if(!(0<e.parents(r).length||"embed"===this.tagName.toLowerCase()&&e.parent("object").length||e.parent(".fluid-width-video-wrapper").length)){e.css("height")||e.css("width")||!isNaN(e.attr("height"))&&!isNaN(e.attr("width"))||(e.attr("height",9),e.attr("width",16));var t=("object"===this.tagName.toLowerCase()||e.attr("height")&&!isNaN(parseInt(e.attr("height"),10))?parseInt(e.attr("height"),10):e.height())/(isNaN(parseInt(e.attr("width"),10))?e.width():parseInt(e.attr("width"),10));if(!e.attr("name")){var i="fitvid"+n.fn.fitVids._count;e.attr("name",i),n.fn.fitVids._count++}e.wrap('<div class="fluid-width-video-container"><div class="fluid-width-video-wrapper"></div></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*t+"%"),e.removeAttr("height").removeAttr("width")}})})},n.fn.fitVids._count=0}(window.jQuery||window.Zepto),function(c,i){c.Casper||(c.Casper={}),c.Casper.floatingHeader=function(){var r=i.querySelector("#reading-progress"),n=i.querySelector(".floating-header"),o=i.querySelector(".post-full-title"),a=c.scrollY,s=c.innerHeight,d=i.body.clientHeight,l=!1;function e(){l||requestAnimationFrame(t),l=!0}function t(){var e=o.getBoundingClientRect().top+c.scrollY,t=o.offsetHeight+35,i=d-s;e+t<=a?n.classList.add("floating-active"):n.classList.remove("floating-active"),r.setAttribute("max",i),r.setAttribute("value",a),l=!1}c.addEventListener("scroll",function(){a=c.scrollY,e()},{passive:!0}),c.addEventListener("resize",function(){s=c.innerHeight,d=i.body.clientHeight,e()},!1),t()}}(window,document),function(e,t){t.addEventListener("DOMContentLoaded",function(){t.querySelectorAll(".kg-gallery-image img").forEach(function(e){var t=e.closest(".kg-gallery-image"),i=e.attributes.width.value/e.attributes.height.value;t.style.flex=i+" 1 0%"})})}(window,document),function(t,i){var r=i.querySelector("link[rel=next]");if(r){var n=i.querySelector(".post-feed");if(n){var o=300,a=!1,s=!1,d=t.scrollY,l=t.innerHeight,c=i.documentElement.scrollHeight;t.addEventListener("scroll",f,{passive:!0}),t.addEventListener("resize",v),h()}}function u(){if(404===this.status)return t.removeEventListener("scroll",f),void t.removeEventListener("resize",v);this.response.querySelectorAll(".post-card").forEach(function(e){n.appendChild(e)});var e=this.response.querySelector("link[rel=next]");e?r.href=e.href:(t.removeEventListener("scroll",f),t.removeEventListener("resize",v)),c=i.documentElement.scrollHeight,s=a=!1}function e(){if(!s)if(d+l<=c-o)a=!1;else{s=!0;var e=new t.XMLHttpRequest;e.responseType="document",e.addEventListener("load",u),e.open("GET",r.href),e.send(null)}}function h(){a||t.requestAnimationFrame(e),a=!0}function f(){d=t.scrollY,h()}function v(){l=t.innerHeight,c=i.documentElement.scrollHeight,h()}}(window,document);
//# sourceMappingURL=casper.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,2 +0,0 @@
!function(n,t){var r=t.querySelector("link[rel=next]");if(r){var i=t.querySelector(".post-feed");if(i){var o=300,s=!1,l=!1,c=n.scrollY,u=n.innerHeight,d=t.documentElement.scrollHeight;n.addEventListener("scroll",a,{passive:!0}),n.addEventListener("resize",m),f()}}function v(){if(404===this.status)return n.removeEventListener("scroll",a),void n.removeEventListener("resize",m);this.response.querySelectorAll(".post-card").forEach(function(e){i.appendChild(e)});var e=this.response.querySelector("link[rel=next]");e?r.href=e.href:(n.removeEventListener("scroll",a),n.removeEventListener("resize",m)),d=t.documentElement.scrollHeight,l=s=!1}function e(){if(!l)if(c+u<=d-o)s=!1;else{l=!0;var e=new n.XMLHttpRequest;e.responseType="document",e.addEventListener("load",v),e.open("GET",r.href),e.send(null)}}function f(){s||n.requestAnimationFrame(e),s=!0}function a(){c=n.scrollY,f()}function m(){u=n.innerHeight,d=t.documentElement.scrollHeight,f()}}(window,document);
//# sourceMappingURL=infinitescroll.js.map

View file

@ -1 +0,0 @@
{"version":3,"sources":["infinitescroll.js"],"names":["window","document","nextElement","querySelector","feedElement","buffer","ticking","loading","lastScrollY","scrollY","lastWindowHeight","innerHeight","lastDocumentHeight","documentElement","scrollHeight","addEventListener","onScroll","passive","onResize","requestTick","onPageLoad","this","status","removeEventListener","response","querySelectorAll","forEach","item","appendChild","resNextElement","href","onUpdate","xhr","XMLHttpRequest","responseType","open","send","requestAnimationFrame"],"mappings":"CAIA,SAAUA,EAAQC,GAEd,IAAIC,EAAcD,EAASE,cAAc,kBACzC,GAAKD,EAAL,CAGA,IAAIE,EAAcH,EAASE,cAAc,cACzC,GAAKC,EAAL,CAEA,IAAIC,EAAS,IAETC,GAAU,EACVC,GAAU,EAEVC,EAAcR,EAAOS,QACrBC,EAAmBV,EAAOW,YAC1BC,EAAqBX,EAASY,gBAAgBC,aAmElDd,EAAOe,iBAAiB,SAAUC,EAAU,CAAEC,SAAS,IACvDjB,EAAOe,iBAAiB,SAAUG,GAElCC,KApEA,SAASC,IACL,GAAoB,MAAhBC,KAAKC,OAGL,OAFAtB,EAAOuB,oBAAoB,SAAUP,QACrChB,EAAOuB,oBAAoB,SAAUL,GAKtBG,KAAKG,SAASC,iBAAiB,cACrCC,QAAQ,SAAUC,GAC3BvB,EAAYwB,YAAYD,KAI5B,IAAIE,EAAiBR,KAAKG,SAASrB,cAAc,kBAC7C0B,EACA3B,EAAY4B,KAAOD,EAAeC,MAElC9B,EAAOuB,oBAAoB,SAAUP,GACrChB,EAAOuB,oBAAoB,SAAUL,IAIzCN,EAAqBX,EAASY,gBAAgBC,aAE9CP,EADAD,GAAU,EAId,SAASyB,IAEL,IAAIxB,EAGJ,GAAIC,EAAcE,GAAoBE,EAAqBP,EACvDC,GAAU,MADd,CAKAC,GAAU,EAEV,IAAIyB,EAAM,IAAIhC,EAAOiC,eACrBD,EAAIE,aAAe,WAEnBF,EAAIjB,iBAAiB,OAAQK,GAE7BY,EAAIG,KAAK,MAAOjC,EAAY4B,MAC5BE,EAAII,KAAK,OAGb,SAASjB,IACLb,GAAWN,EAAOqC,sBAAsBN,GACxCzB,GAAU,EAGd,SAASU,IACLR,EAAcR,EAAOS,QACrBU,IAGJ,SAASD,IACLR,EAAmBV,EAAOW,YAC1BC,EAAqBX,EAASY,gBAAgBC,aAC9CK,KAhFR,CAuFGnB,OAAQC","file":"infinitescroll.js","sourcesContent":["/**\n * Infinite Scroll\n */\n\n(function(window, document) {\n // next link element\n var nextElement = document.querySelector('link[rel=next]');\n if (!nextElement) return;\n\n // post feed element\n var feedElement = document.querySelector('.post-feed');\n if (!feedElement) return;\n\n var buffer = 300;\n\n var ticking = false;\n var loading = false;\n\n var lastScrollY = window.scrollY;\n var lastWindowHeight = window.innerHeight;\n var lastDocumentHeight = document.documentElement.scrollHeight;\n\n function onPageLoad() {\n if (this.status === 404) {\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('resize', onResize);\n return;\n }\n\n // append contents\n var postElements = this.response.querySelectorAll('.post-card');\n postElements.forEach(function (item) {\n feedElement.appendChild(item);\n });\n\n // set next link\n var resNextElement = this.response.querySelector('link[rel=next]');\n if (resNextElement) {\n nextElement.href = resNextElement.href;\n } else {\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('resize', onResize);\n }\n\n // sync status\n lastDocumentHeight = document.documentElement.scrollHeight;\n ticking = false;\n loading = false;\n }\n\n function onUpdate() {\n // return if already loading\n if (loading) return;\n\n // return if not scroll to the bottom\n if (lastScrollY + lastWindowHeight <= lastDocumentHeight - buffer) {\n ticking = false;\n return;\n }\n\n loading = true;\n\n var xhr = new window.XMLHttpRequest();\n xhr.responseType = 'document';\n\n xhr.addEventListener('load', onPageLoad);\n\n xhr.open('GET', nextElement.href);\n xhr.send(null);\n }\n\n function requestTick() {\n ticking || window.requestAnimationFrame(onUpdate);\n ticking = true;\n }\n\n function onScroll() {\n lastScrollY = window.scrollY;\n requestTick();\n }\n\n function onResize() {\n lastWindowHeight = window.innerHeight;\n lastDocumentHeight = document.documentElement.scrollHeight;\n requestTick();\n }\n\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('resize', onResize);\n\n requestTick();\n})(window, document);\n"]}

View file

@ -1,2 +0,0 @@
!function(d){"use strict";d.fn.fitVids=function(t){var i={customSelector:null,ignore:null};if(!document.getElementById("fit-vids-style")){var e=document.head||document.getElementsByTagName("head")[0],r=document.createElement("div");r.innerHTML='<p>x</p><style id="fit-vids-style">.fluid-width-video-container{flex-grow: 1;width:100%;}.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>',e.appendChild(r.childNodes[1])}return t&&d.extend(i,t),this.each(function(){var t=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"];i.customSelector&&t.push(i.customSelector);var r=".fitvidsignore";i.ignore&&(r=r+", "+i.ignore);var e=d(this).find(t.join(","));(e=(e=e.not("object object")).not(r)).each(function(){var t=d(this);if(!(0<t.parents(r).length||"embed"===this.tagName.toLowerCase()&&t.parent("object").length||t.parent(".fluid-width-video-wrapper").length)){t.css("height")||t.css("width")||!isNaN(t.attr("height"))&&!isNaN(t.attr("width"))||(t.attr("height",9),t.attr("width",16));var e=("object"===this.tagName.toLowerCase()||t.attr("height")&&!isNaN(parseInt(t.attr("height"),10))?parseInt(t.attr("height"),10):t.height())/(isNaN(parseInt(t.attr("width"),10))?t.width():parseInt(t.attr("width"),10));if(!t.attr("name")){var i="fitvid"+d.fn.fitVids._count;t.attr("name",i),d.fn.fitVids._count++}t.wrap('<div class="fluid-width-video-container"><div class="fluid-width-video-wrapper"></div></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*e+"%"),t.removeAttr("height").removeAttr("width")}})})},d.fn.fitVids._count=0}(window.jQuery||window.Zepto);
//# sourceMappingURL=jquery.fitvids.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,73 @@
/* eslint-env browser */
/**
* Floating header
* Used on invividual post pages, displays a sticky header with progress indicator
*
* This JS is automatically applied for any template where you use the
* {{> floating-header}} partial
*/
(function (window, document) {
// set up Casper as a global object
if (!window.Casper) {
window.Casper = {};
}
window.Casper.floatingHeader = function floatingHeader() {
// NOTE: Scroll performance is poor in Safari
// - this appears to be due to the events firing much more slowly in Safari.
// Dropping the scroll event and using only a raf loop results in smoother
// scrolling but continuous processing even when not scrolling
var progressBar = document.querySelector('#reading-progress');
var header = document.querySelector('.floating-header');
var title = document.querySelector('.post-full-title');
var lastScrollY = window.scrollY;
var lastWindowHeight = window.innerHeight;
var lastDocumentHeight = document.body.clientHeight;
var ticking = false;
function onScroll() {
lastScrollY = window.scrollY;
requestTick();
}
function onResize() {
lastWindowHeight = window.innerHeight;
lastDocumentHeight = document.body.clientHeight;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(update);
}
ticking = true;
}
function update() {
var trigger = title.getBoundingClientRect().top + window.scrollY;
var triggerOffset = title.offsetHeight + 35;
var progressMax = lastDocumentHeight - lastWindowHeight;
// show/hide floating header
if (lastScrollY >= trigger + triggerOffset) {
header.classList.add('floating-active');
} else {
header.classList.remove('floating-active');
}
progressBar.setAttribute('max', progressMax);
progressBar.setAttribute('value', lastScrollY);
ticking = false;
}
window.addEventListener('scroll', onScroll, {passive: true});
window.addEventListener('resize', onResize, false);
update();
};
})(window, document);

24
assets/js/gallery-card.js Normal file
View file

@ -0,0 +1,24 @@
/* eslint-env browser */
/**
* Gallery card support
* Used on any individual post/page
*
* Detects when a gallery card has been used and applies sizing to make sure
* the display matches what is seen in the editor.
*/
(function (window, document) {
var resizeImagesInGalleries = function resizeImagesInGalleries() {
var images = document.querySelectorAll('.kg-gallery-image img');
images.forEach(function (image) {
var container = image.closest('.kg-gallery-image');
var width = image.attributes.width.value;
var height = image.attributes.height.value;
var ratio = width / height;
container.style.flex = ratio + ' 1 0%';
});
};
document.addEventListener('DOMContentLoaded', resizeImagesInGalleries);
})(window, document);

View file

@ -1,15 +1,30 @@
/* eslint-env browser */
/**
* Infinite Scroll
* Used on all pages where there is a list of posts (homepage, tag index, etc).
*
* When the page is scrolled to 300px from the bottom, the next page of posts
* is fetched by following the the <link rel="next" href="..."> that is output
* by {{ghost_head}}.
*
* The individual post items are extracted from the fetched pages by looking for
* a wrapper element with the class "post-card". Any found elements are appended
* to the element with the class "post-feed" in the currently viewed page.
*/
(function (window, document) {
// next link element
var nextElement = document.querySelector('link[rel=next]');
if (!nextElement) return;
if (!nextElement) {
return;
}
// post feed element
var feedElement = document.querySelector('.post-feed');
if (!feedElement) return;
if (!feedElement) {
return;
}
var buffer = 300;
@ -50,7 +65,9 @@
function onUpdate() {
// return if already loading
if (loading) return;
if (loading) {
return;
}
// return if not scroll to the bottom
if (lastScrollY + lastWindowHeight <= lastDocumentHeight - buffer) {

View file

@ -55,27 +55,14 @@
</div>
{{/if}}
<script>
var images = document.querySelectorAll('.kg-gallery-image img');
images.forEach(function (image) {
var container = image.closest('.kg-gallery-image');
var width = image.attributes.width.value;
var height = image.attributes.height.value;
var ratio = width / height;
container.style.flex = ratio + ' 1 0%';
})
</script>
{{!-- jQuery + Fitvids, which makes all video embeds responsive --}}
{{!-- jQuery, required for fitvids --}}
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="{{asset "built/jquery.fitvids.js"}}"></script>
<script src="{{asset "built/infinitescroll.js"}}"></script>
{{!-- Fitvids (for responsive video embeds), infinite scroll, floating header, and gallery card support --}}
<script src="{{asset "built/casper.js"}}"></script>
{{!-- The #block helper will pull in data from the #contentFor other template files. In this case, there's some JavaScript which we only want to use in post.hbs, but it needs to be included down here, after jQuery has already loaded. --}}
{{{block "scripts"}}}

View file

@ -5,6 +5,7 @@ const pump = require('pump');
const livereload = require('gulp-livereload');
const postcss = require('gulp-postcss');
const zip = require('gulp-zip');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const beeper = require('beeper');
const fs = require('fs');
@ -56,7 +57,12 @@ function css(done) {
function js(done) {
pump([
src('assets/js/*.js', {sourcemaps: true}),
src([
// pull in lib files first so our own code can depend on it
'assets/js/lib/*.js',
'assets/js/*.js'
], {sourcemaps: true}),
concat('casper.js'),
uglify(),
dest('assets/built/', {sourcemaps: '.'}),
livereload()

View file

@ -51,6 +51,7 @@
"cssnano": "4.1.10",
"gscan": "3.0.0",
"gulp": "4.0.2",
"gulp-concat": "^2.6.1",
"gulp-livereload": "4.0.2",
"gulp-postcss": "8.0.0",
"gulp-uglify": "3.0.2",

View file

@ -26,3 +26,11 @@
</div>
</progress>
</div>
{{#contentFor "scripts"}}
<script>
$(document).ready(function () {
Casper.floatingHeader();
})
</script>
{{/contentFor}}

View file

@ -145,67 +145,9 @@ into the {body} of the default.hbs template --}}
{{!-- The #contentFor helper here will send everything inside it up to the matching #block helper found in default.hbs --}}
{{#contentFor "scripts"}}
<script>
// NOTE: Scroll performance is poor in Safari
// - this appears to be due to the events firing much more slowly in Safari.
// Dropping the scroll event and using only a raf loop results in smoother
// scrolling but continuous processing even when not scrolling
$(document).ready(function () {
// Start fitVids
var $postContent = $(".post-full-content");
$postContent.fitVids();
// End fitVids
var progressBar = document.querySelector('#reading-progress');
var header = document.querySelector('.floating-header');
var title = document.querySelector('.post-full-title');
var lastScrollY = window.scrollY;
var lastWindowHeight = window.innerHeight;
var lastDocumentHeight = $(document).height();
var ticking = false;
function onScroll() {
lastScrollY = window.scrollY;
requestTick();
}
function onResize() {
lastWindowHeight = window.innerHeight;
lastDocumentHeight = $(document).height();
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(update);
}
ticking = true;
}
function update() {
var trigger = title.getBoundingClientRect().top + window.scrollY;
var triggerOffset = title.offsetHeight + 35;
var progressMax = lastDocumentHeight - lastWindowHeight;
// show/hide floating header
if (lastScrollY >= trigger + triggerOffset) {
header.classList.add('floating-active');
} else {
header.classList.remove('floating-active');
}
progressBar.setAttribute('max', progressMax);
progressBar.setAttribute('value', lastScrollY);
ticking = false;
}
window.addEventListener('scroll', onScroll, {passive: true});
window.addEventListener('resize', onResize, false);
update();
});
</script>
{{/contentFor}}

View file

@ -674,6 +674,13 @@ concat-stream@^1.5.2, concat-stream@^1.6.0:
readable-stream "^2.2.2"
typedarray "^0.0.6"
concat-with-sourcemaps@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz#d4ea93f05ae25790951b99e7b3b09e3908a4082e"
integrity sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg==
dependencies:
source-map "^0.6.1"
config-chain@~1.1.5:
version "1.1.12"
resolved "https://registry.yarnpkg.com/config-chain/-/config-chain-1.1.12.tgz#0fde8d091200eb5e808caf25fe618c02f48e4efa"
@ -1672,6 +1679,15 @@ gulp-cli@^2.2.0:
v8flags "^3.0.1"
yargs "^7.1.0"
gulp-concat@^2.6.1:
version "2.6.1"
resolved "https://registry.yarnpkg.com/gulp-concat/-/gulp-concat-2.6.1.tgz#633d16c95d88504628ad02665663cee5a4793353"
integrity sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M=
dependencies:
concat-with-sourcemaps "^1.0.0"
through2 "^2.0.0"
vinyl "^2.0.0"
gulp-livereload@4.0.2:
version "4.0.2"
resolved "https://registry.yarnpkg.com/gulp-livereload/-/gulp-livereload-4.0.2.tgz#fc8a75c7511cd65afd2202cbcdc8bb0f8dde377b"