Skip to content
Permalink
Browse files

refactor script/style injection

  • Loading branch information...
ikeq committed Jun 28, 2019
1 parent 8d65864 commit c6984ae819fb14dcd4cb01068c9f4f706c52fbd8
@@ -376,7 +376,7 @@ pwa:

# Plugins
# Inject html snippet to a specified position,
# Or global inject additional scripts/styles.
# Or global inject scripts/styles.
# plugins:
# # Dynamic inject html snippet
# - position: # `sidebar` | `post` | `page` | `comments`, can be an array
@@ -389,42 +389,41 @@ pwa:
# # ```
# template:

# # Inject additional scripts/styles resources
# # Global Inject scripts/styles
# # scripts will be injected into <body>, and styles will be injected into <head>
# - resources:
# # In general, script or style depends on their ext name.
# - //xxx.css
# - //xxx.js

# # A few more flexible examples

# # <script src="//sample.com/api.php?format=jsonp" id="sample-api" whatever></script>
# - tag: script # html tag, `script` | `style` | `link`
# # Any possible attributes
# src: //sample.com/api.php?format=jsonp
# id: sample-api
# whatever: true

# # <link rel="stylesheet" href="xxx.css" disable>
# - tag: link
# href: xxx.css
# disable: true

# # Inline script
# # <script type="text/x-mathjax-config">MathJax.Hub.Config({...})</script>
# - tag: script
# type: text/x-mathjax-config
# code: |
# MathJax.Hub.Config({
# showProcessingMessages: false,
# messageStyle: 'none',
# tex2jax: { inlineMath: [['s;,'s;], ['\\(','\\)']] }
# })

# # Inline style
# # <style>.mycss{...}</style>
# - tag: style
# code: |
# .mycss {
# color: rebeccapurple;
# }
# # In general, script or style depends on their ext name.
# - //xxx.css
# - //xxx.js

# # A few more flexible examples

# # <script src="//sample.com/api.php?format=jsonp" id="sample-api" defer></script>
# - tag: script # html tag, `script` | `style` | `link`
# # Any possible attributes
# src: //sample.com/api.php?format=jsonp
# id: sample-api
# defer: true

# # <link rel="stylesheet" href="xxx.css" disable>
# - tag: link
# href: xxx.css
# disable: true

# # Inline script
# # <script type="text/x-mathjax-config">MathJax.Hub.Config({...})</script>
# - tag: script
# type: text/x-mathjax-config
# code: |
# MathJax.Hub.Config({
# showProcessingMessages: false,
# messageStyle: 'none',
# tex2jax: { inlineMath: [['s;,'s;], ['\\(','\\)']] }
# })

# # Inline style
# # <style>.mycss{...}</style>
# - tag: style
# code: |
# .mycss {
# color: rebeccapurple;
# }
@@ -13,18 +13,18 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<% } -%>
<%- open_graph({ image: page.thumbnail || theme.profile.avatar }) %>
<% if (theme.seo.structured_data) { %><%- structured_data(page) %><% } -%>
<% if (config.feed && config.feed.path) { -%>
<link rel="alternate" type="application/atom+xml" title="<%= config.title %>" href="<%= url_for(config.feed.path) %>">
<% } -%>
<% if (theme.appearance.font && theme.appearance.font.url) { -%><%- css(theme.appearance.font.url) -%><% } %>
<%- theme_static('css') %>
<%- theme.styles %>
<% if (theme.runtime.themeHash) { %><%- css('theme.' + theme.runtime.themeHash) %><% } %>
<%- js('config.' + theme.runtime.configHash) %>
<% if (theme.seo.structured_data) { %><%- structured_data(page) %><% } -%>
<% if (theme.ga) { %><%- ga(theme.ga) %><% } -%>
</head>
<body lang="<%= config.language || 'en' %>">
<is-d2a57d></is-d2a57d>
<%- theme_static('js') -%>
<%- theme.scripts -%>
</body>
</html>
@@ -1,9 +1,10 @@
const utils = require('./utils');
const gravatar = require('hexo/lib/plugins/helper/gravatar');
const cheerio = require('cheerio');
const gravatar = require('hexo/lib/plugins/helper/gravatar');
const urlFor = require('hexo/lib/plugins/helper/url_for');
const utils = require('./utils');
const pkg = require('../package.json');
const configSchema = require('./configSchema.json');
const resources = require('../source/_resources.json');

module.exports = function (hexo) {
hexo.on('generateBefore', function () {
@@ -20,6 +21,7 @@ module.exports = function (hexo) {
$title: site.title,
$description: site.description
});
const urlFn = result.static_prefix ? a => `${result.static_prefix}/${a}` : urlFor.bind(this);

if (!result.data_prefix) result.data_prefix = result.data_dir;

@@ -40,19 +42,16 @@ module.exports = function (hexo) {
result.sns = sns;
}

/**
* convert plugins into the following format
*
* {
* $t: ['0', '1', '2', '3'],
* sidebar: [indexes],
* post: [indexes],
* page: [indexes],
* comments: [indexes]
* }
*/
if (result.plugins) {
result.plugins = [
...resources.styles,
...resources.scripts,
resources.locales[site.languages || 'en'],
...(result.plugins || [])
];
{
const plugins = { $t: [] };
const scripts = [];
const styles = [];
let minify;
try {
const htmlMinify = require('html-minifier').minify;
@@ -66,8 +65,32 @@ module.exports = function (hexo) {
minify = o => o;
}
result.plugins.forEach(plugin => {
// Positioned plugins
if (plugin.position) {
// Tags
if (typeof plugin === 'string' || plugin.tag) {
// Direct with url
if (!plugin.tag) {
const tag = plugin.split('?')[0].endsWith('.css') ? 'link' : 'script';
plugin = tag === 'link' ? { tag, href: plugin } : { tag, src: plugin }
}
if (plugin.tag === 'link' && !plugin.rel) plugin.rel = 'stylesheet';
if (plugin.src) plugin.src = urlFn(plugin.src);
if (plugin.href) plugin.href = urlFn(plugin.href);

(plugin.tag === 'script' ? scripts : styles).push(utils.tag(plugin));
}

/**
* Positioned plugins
* convert into the following format
* {
* $t: ['0', '1', '2', '3'],
* sidebar: [indexes],
* post: [indexes],
* page: [indexes],
* comments: [indexes]
* }
*/
else {
const $ = cheerio.load(plugin.template, { decodeEntities: false });
const index = plugins.$t.length;

@@ -79,16 +102,14 @@ module.exports = function (hexo) {
});
plugins.$t.push(minify($.html()));

(Array.isArray(plugin.position) ? plugin.position : [plugin.position]).forEach(p => (plugins[p] || (plugins[p] = [])).push(index));
}

// Tags
else {
//
(Array.isArray(plugin.position) ? plugin.position : [plugin.position])
.forEach(p => (plugins[p] || (plugins[p] = [])).push(index));
}
});

result.plugins = plugins;
result.styles = styles.join('\n');
result.scripts = scripts.join('\n');
}

// override boolean value to html string
@@ -26,7 +26,7 @@
"properties": {
"accent_color": { "$ref": "#/definitions/color" },
"background": {
"oneOf":[
"oneOf": [
{ "type": "string" },
{ "type": "array", "items": { "type": "string" }, "minItems": 1, "maxItems": 2 }
]
@@ -307,8 +307,8 @@
"position": { "enum": ["sidebar", "post", "page", "comments"] }
},
"items": {
"type": "object",
"oneOf": [
{ "type": "string" },
{
"type": "object",
"properties": {
@@ -326,18 +326,9 @@
{
"type": "object",
"properties": {
"resources": {
"type": "array",
"items": {
"type": "object",
"properties": {
"tag": { "enum": ["script", "style", "link"] }
},
"required": ["tag"]
}
}
"tag": { "enum": ["script", "style", "link"] }
},
"required": ["resources"]
"required": ["tag"]
}
]
}
@@ -1,6 +1,5 @@
module.exports = function (hexo) {
hexo.extend.helper.register('url_trim', require('./url_trim'));
hexo.extend.helper.register('theme_static', require('./theme_static'));
hexo.extend.helper.register('structured_data', require('./structured_data'));
hexo.extend.helper.register('ga', require('./ga'));
};

This file was deleted.

@@ -635,3 +635,24 @@ exports.snippet = function (code, template = code => `<script>${code}</script>`)
exports.published = function (p) {
return Boolean(~['post', 'page'].indexOf(p.layout));
}

/**
* Render tag object to string
*
* @param {VTag} vTag
* @returns {string}
*/
exports.tag = function (vTag) {
const { tag, code, ...attrs } = vTag;

if (code) return `<${tag}>${code}</${tag}>`;

let attrString = '';
for (let k in attrs) {
const v = attrs[k]
if (v === true) attrString += ' ' + k;
else attrString += ` ${k}="${v}"`;
}
if (tag === 'script') return `<script${attrString}></script>`;
if (tag === 'link') return `<link${attrString}>`;
}
@@ -0,0 +1 @@
{"styles":["styles.6413cb5fd384752f1714.css"],"scripts":["runtime.9c308a63d02029c20228.js","polyfills-es5.613d1909ec381c0aefb7.js","polyfills.23aa31104b29f3163090.js"],"locales":{"en":"main.c0d55e7428280128d494.en.js","zh-Hant":"main.12166a654353e0a82d68.zh-Hant.js","zh-Hans":"main.3a9ad2f49fd8634e7fa0.zh-Hans.js","ja":"main.e01c85758301d20058a7.ja.js"}}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

0 comments on commit c6984ae

Please sign in to comment.
You can’t perform that action at this time.