Created
November 13, 2017 23:04
-
-
Save hejrobin/7fced661bd6208b5f225c723c9dbeb5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function( global ) { | |
var scriptRootNode; | |
var scriptNamespace = 'embed'; | |
var scriptNameRegex = /.*embed.js/; | |
var scriptPath = 'https://domain.tld/widget-app.js'; | |
var stylePath = 'https://domain.tld/widget-app.css'; | |
if ( ! global[ scriptNamespace ] ) | |
global[ scriptNamespace ] = {}; | |
var scriptEmbed = global[ scriptNamespace ]; | |
if ( ! scriptEmbed.isEmbedded ) | |
scriptEmbed.isEmbedded = false; | |
var scriptTags = document.getElementsByTagName( 'script' ); | |
var loadJavaScriptResource = function( resourcePath, onLoadCallback ) { | |
var scriptNode = document.createElement( 'script' ); | |
scriptNode.type = 'text/javascript'; | |
scriptNode.src = resourcePath; | |
scriptNode.charset = 'utf-8'; | |
scriptNode.async = false; | |
if ( typeof onLoadCallback === 'function' ) | |
scriptNode.onload = onLoadCallback; | |
document.getElementsByTagName( 'head' )[ 0 ].appendChild( scriptNode ); | |
}; | |
var loadStylesheetResource = function( resourcePath ) { | |
var styleNode = document.createElement( 'link' ); | |
styleNode.type = 'text/css'; | |
styleNode.rel = 'stylesheet'; | |
styleNode.href = resourcePath; | |
document.getElementsByTagName( 'head' )[ 0 ].appendChild( styleNode ); | |
}; | |
if ( scriptTags.length > 0 ) { | |
for ( var i = 0, l = scriptTags.length; i < l; i++ ) { | |
scriptRootNode = scriptTags[ i ]; | |
var matches = scriptTag.src.match( scriptNameRegex ); | |
if ( matches !== null && matches.length > 0 && scriptEmbed.isEmbedded === false ) { | |
loadJavaScriptResource( scriptPath ); | |
loadStylesheetResource( stylePath ); | |
scriptEmbed.isEmbedded = true; | |
break; | |
} | |
} | |
} | |
global[ scriptNamespace ] = scriptEmbed; | |
}( this )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment