remove inline scripts as possible

This commit is contained in:
Pig Fang 2020-06-11 19:27:15 +08:00
parent 9f6cec56a8
commit 86c39e6b12
25 changed files with 105 additions and 82 deletions

1
.gitignore vendored
View File

@ -27,3 +27,4 @@ storage/options.php
.php_cs.cache
resources/views/overrides
public/sw.js
public/meta.js

View File

@ -43,6 +43,7 @@ class HeadComposer
$this->seo($view);
$this->injectStyles($view);
$this->addExtra($view);
$this->serializeGlobals($view);
}
public function addFavicon(View $view)
@ -112,7 +113,7 @@ class HeadComposer
'integrity' => 'sha256-h20CPZ0QyXlBuAw7A+KluUYx/3pK+c7lYEpqLTlxjYQ=',
'crossorigin' => 'anonymous',
];
if (!$this->request->is('/')) {
if (!$this->request->is('/') && config('app.asset.env') !== 'development') {
$links[] = [
'rel' => 'stylesheet',
'href' => $this->webpack->url('style.css'),
@ -131,4 +132,18 @@ class HeadComposer
$this->dispatcher->dispatch(new \App\Events\RenderingHeader($content));
$view->with('extra_head', $content);
}
public function serializeGlobals(View $view)
{
$blessing = [
'version' => config('app.version'),
'locale' => config('app.locale'),
'base_url' => url('/'),
'site_name' => option_localized('site_name'),
'route' => request()->path(),
'i18n' => new \stdClass(),
'extra' => [],
];
$view->with('blessing', $blessing);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace App\Listeners;
use stdClass;
class SerializeGlobals
{
public function handle($event)
{
$blessing = [
'version' => config('app.version'),
'locale' => config('app.locale'),
'base_url' => url('/'),
'site_name' => option_localized('site_name'),
'route' => request()->path(),
'i18n' => new stdClass(),
'extra' => [],
];
$event->addContent('<script>window.blessing = '.json_encode($blessing).';</script>');
}
}

View File

@ -20,9 +20,6 @@ class EventServiceProvider extends ServiceProvider
'App\Events\PluginBootFailed' => [
Listeners\NotifyFailedPlugin::class,
],
'App\Events\RenderingHeader' => [
Listeners\SerializeGlobals::class,
],
'auth.registration.completed' => [
Listeners\SendEmailVerification::class,
],

View File

@ -11,7 +11,7 @@
"private": true,
"scripts": {
"dev": "webpack-dev-server",
"build": "webpack --mode=production -p --progress",
"build": "webpack -p --progress && webpack -p --config=webpack.meta.config.js",
"lint": "eslint --ext=ts -f=beauty .",
"fmt": "prettier --write resources/assets",
"test": "jest",
@ -198,6 +198,7 @@
"coveragePathIgnorePatterns": [
"/node_modules/",
"<rootDir>/resources/assets/src/styles",
"<rootDir>/resources/assets/src/scripts/extra.ts",
"<rootDir>/resources/assets/src/scripts/urls.ts",
"<rootDir>/resources/assets/tests/setup",
"<rootDir>/resources/assets/tests/utils",

View File

@ -1,4 +1,5 @@
import './init' // Must be first
import './extra'
import './i18n'
import './net'
import './event'

View File

@ -0,0 +1,12 @@
export function getExtraData(): any {
const jsonElement = document.querySelector('#blessing-extra')
/* istanbul ignore next */
if (jsonElement) {
return JSON.parse(jsonElement.textContent ?? '{}')
}
}
const extraData = getExtraData()
if (extraData) {
blessing.extra = extraData
}

View File

@ -1,4 +1,5 @@
import '@/styles/home.css'
import { getExtraData } from './extra'
export function scrollHander() {
const header = document.querySelector('.navbar')
@ -28,8 +29,11 @@ export async function logout() {
}
/* istanbul ignore next */
if (blessing.extra.transparent_navbar) {
window.addEventListener('load', scrollHander)
if (process.env.NODE_ENV !== 'test') {
const { transparent_navbar }: { transparent_navbar: boolean } = getExtraData()
if (transparent_navbar) {
window.addEventListener('load', scrollHander)
}
}
/* istanbul ignore next */
document

View File

@ -0,0 +1,9 @@
{
const blessingElement = document.querySelector('#blessing-globals')!
// @ts-ignore
window.blessing = JSON.parse(blessingElement.textContent!)
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js?v4')
})
}

View File

@ -71,7 +71,7 @@
{% endblock %}
{% block before_foot %}
<script>
blessing.extra = {{ extra|json_encode|raw }}
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -4,7 +4,7 @@
{% block before_foot %}
{% set extra = {'currentUser': auth_user()} %}
<script>
blessing.extra = {{ extra|json_encode|raw }}
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -13,10 +13,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
configurable: false,
get: () => Object.freeze({{ extra|json_encode|raw }})
})
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -9,10 +9,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
configurable: false,
get: () => Object.freeze({{ extra|json_encode|raw }})
})
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -9,10 +9,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
configurable: false,
get: () => Object.freeze({{ extra|json_encode|raw }})
})
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -158,8 +158,8 @@
{% if home_page_css_loader %}
<script src="{{ home_page_css_loader }}"></script>
{% endif %}
<script>
blessing.extra = { transparent_navbar: {{ transparent_navbar ? 'true' : 'false' }} }
<script type="application/json" id="blessing-extra">
{{ {transparent_navbar: transparent_navbar}|json_encode|raw }}
</script>
{{ include('shared.foot') }}
</body>

View File

@ -10,11 +10,8 @@
{% if custom_cdn_host %}
<link rel="preconnect" href="{{ custom_cdn_host }}" crossorigin>
{% endif %}
<script>
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js?v4')
})
</script>
<script id="blessing-globals" type="application/json">{{ blessing|json_encode|raw }}</script>
<script src="{{ url('/meta.js') }}"></script>
{% for link in links %}
<link{% for attribute, value in link %} {{ attribute }}="{{ value|raw }}"{% endfor %}>
{% endfor %}

View File

@ -7,7 +7,7 @@
{% endblock %}
{% block before_foot %}
<script>
blessing.extra = {{ {currentUid: auth_user().uid}|json_encode|raw }}
<script id="blessing-extra" type="application/json">
{{ {currentUid: auth_user().uid}|json_encode|raw }}
</script>
{% endblock %}

View File

@ -30,10 +30,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
configurable: false,
get: () => Object.freeze({{ extra|json_encode|raw }})
})
</script>
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -27,7 +27,7 @@
{% endblock %}
{% block before_foot %}
<script>
blessing.extra = {{ extra|json_encode|raw }}
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -9,9 +9,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
get: () => Object.freeze({{ extra|json_encode|raw }})
})
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -36,9 +36,7 @@
{% endblock %}
{% block before_foot %}
<script>
Object.defineProperty(blessing, 'extra', {
get: () => Object.freeze({{ extra|json_encode|raw }})
})
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -9,5 +9,7 @@
{% endblock %}
{% block before_foot %}
<script>blessing.extra = {{ extra|json_encode|raw }}</script>
<script id="blessing-extra" type="application/json">
{{ extra|json_encode|raw }}
</script>
{% endblock %}

View File

@ -12,7 +12,6 @@ if (Test-Path ./public/app) {
# Run webpack
yarn build
Move-Item -Path ./public/app/sw.js -Destination ./public -Force
if ($Simple) {
exit

View File

@ -11,7 +11,6 @@ const config = {
mode: devMode ? 'development' : 'production',
entry: {
app: ['react-hot-loader/patch', '@/index.tsx'],
sw: '@/scripts/sw.ts',
style: ['@/styles/common.css'],
home: '@/scripts/home-page.ts',
spectre: [
@ -22,12 +21,7 @@ const config = {
},
output: {
path: `${__dirname}/public/app`,
filename: ({ chunk }) =>
chunk.name === 'sw'
? 'sw.js'
: devMode
? '[name].js'
: '[name].[contenthash:7].js',
filename: devMode ? '[name].js' : '[name].[contenthash:7].js',
chunkFilename: devMode ? '[id].js' : '[id].[contenthash:7].js',
},
module: {

29
webpack.meta.config.js Normal file
View File

@ -0,0 +1,29 @@
const devMode = !process.argv.includes('-p')
module.exports = {
mode: devMode ? 'development' : 'production',
entry: {
meta: './resources/assets/src/scripts/meta.ts',
sw: './resources/assets/src/scripts/sw.ts',
},
output: {
path: `${__dirname}/public`,
filename: '[name].js',
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
options: {
configFile: 'tsconfig.build.json',
transpileOnly: true,
},
},
],
},
resolve: {
extensions: ['.js', '.ts', '.tsx', '.json'],
},
stats: 'errors-only',
}