Skip to content

Instantly share code, notes, and snippets.

@radist2s
Created October 25, 2017 14:22
Show Gist options
  • Save radist2s/36e52ccd48d68db969030833f6bcf683 to your computer and use it in GitHub Desktop.
Save radist2s/36e52ccd48d68db969030833f6bcf683 to your computer and use it in GitHub Desktop.
Stroke dash offset transition support detect
/**
* Detects browser's support for SVG stroke-dashoffset transition
*
* @return Promise
**/
window.strokeDashOffsetTransitionSupport = function strokeDashOffsetTransitionSupport() {
const caller = strokeDashOffsetTransitionSupport
if (caller.previousResult) {
return caller.previousResult
}
const transitionEndEventName = getTransitionEndEventName() // External dep https://gist.github.com/radist2s/7ac240782ab847bea202
if (!transitionEndEventName) {
return caller.previousResult = Promise.resolve(false)
}
const svgCode = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 1"><defs><mask></mask></defs><path fill="none" stroke="#000" stroke-miterlimit="10" d="M0 .5h8"/></svg>'
const renderer = document.createElement('div')
renderer.innerHTML = svgCode
const svg = renderer.children[0]
const svgPath = svg.querySelector('path')
// For browser optimization case will put svg on top
svg.style.position = 'absolute'
svg.style.top = 0
svg.style.left = 0
svg.style.opacity = 0.01
svg.style.width = '1px'
svg.style.height = '1px'
const totalLength = svgPath.getTotalLength()
const animationQueue = new RafAnimationQueue // External dep https://gist.github.com/radist2s/6a2c46eaa44ed66dc00d
const transitionDurationMs = 5 // transition detect threshold
let svgPathTransitionEndCallback,
fallbackTimeoutId
const transitionSupportPromise = new Promise(function (resolve) {
animationQueue.add(function () {
document.body.appendChild(svg)
})
animationQueue.add(function () {
svgPath.addEventListener(transitionEndEventName, svgPathTransitionEndCallback = function (event) {
if (event.propertyName !== 'stroke-dashoffset') {
return
}
resolve(true)
})
svgPath.style.strokeDasharray = totalLength
svgPath.style.strokeDashoffset = totalLength
svgPath.style[getTransitionStyleProperty()] = `stroke-dashoffset ${transitionDurationMs}ms linear` // External dep https://gist.github.com/radist2s/316de17dafcdbdb62ab1/edit
})
animationQueue.add(function () {
svgPath.style.strokeDashoffset = 0
fallbackTimeoutId = setTimeout(function () {
resolve(false)
}, Math.max(transitionDurationMs * 10, 300))
})
})
Promise.race([transitionSupportPromise]).then(function () {
svgPath.removeEventListener(transitionEndEventName, svgPathTransitionEndCallback)
clearTimeout(fallbackTimeoutId)
svg.parentNode.removeChild(svg)
})
return caller.previousResult = transitionSupportPromise
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment