-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.vue
84 lines (63 loc) · 2.05 KB
/
index.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<template lang='pug'>
section
.html(ref="html", v-html="markup")
transition(v-if="showLoading", name="fade"): .loading(v-if="loading") Loading
</template>
<!-- ––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– -->
<script lang='coffee'>
# Get the script tags from string
# https://regex101.com/r/doKHCZ/1
# https://stackoverflow.com/a/19188718/59160
scriptsPattern = /<script[\s\S]*?>[\s\S]*?<\/script>/gi
# Get script URL from string
# https://regex101.com/r/14IX5a/2
# https://stackoverflow.com/questions/25632144/javascript-regex-to-get-url-from-string-containing-script-tag
scriptURLPattern = /<script[^>]*src=['"](.*?)['"]/gmi
export default
props:
html: String
showLoading:
type: Boolean
default: true
data: ->
loading: true
externalScripts: []
scriptCodes: []
mounted: ->
@parseScripts()
# Load external scripts
try
await Promise.all @externalScripts
@loading = false
# Run inline code
eval code for code in @scriptCodes
# Show an error message to users
catch e then console.error e
computed:
# Get scripts from the html
scripts: -> @html.match(scriptsPattern) || []
# Just the markup without scripts
markup: -> @html.replace scriptsPattern, ''
methods:
# Eval-able JS from scripts array
parseScripts: ->
# iterate through scripts
for script in @scripts
# Render an external script tag
if scriptURL = scriptURLPattern.exec(script)
@externalScripts.push @loadScript scriptURL[1]
# Queue up code to execute
else
@scriptCodes.push script.replace /<\/?script[^>]*>/gi, ''
# add script to head
loadScript: (scriptURL) ->
# Capture html from `this`
target = @$refs.html || document.head
new Promise (resolve, reject) ->
script = document.createElement('script')
script.src = scriptURL
script.async = true
script.onload = resolve
script.onerror= reject
target.appendChild(script)
</script>