怎么按需引入html,react组件实现按需加载.html

var NexT = window.NexT || {};

var CONFIG = {

root: '/',

scheme: 'Mist',

sidebar: {"position":"left","display":"always","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},

fancybox: true,

tabs: true,

motion: true,

duoshuo: {

userId: '0',

author: '博主'

},

algolia: {

applicationID: '',

apiKey: '',

indexName: '',

hits: {"per_page":10},

labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}

}

};

react组件实现按需加载 | cosyer's Blog

var _hmt = _hmt || [];

(function() {

var hm = document.createElement("script");

hm.src = "https://hm.baidu.com/hm.js?653a4be35cb6c7b26817038a17c3f0d6";

var s = document.getElementsByTagName("script")[0];

s.parentNode.insertBefore(hm, s);

})();

// scrollbar滚动条样式优化

::-webkit-scrollbar-corner {

background-color: transparent;

}

::-webkit-scrollbar-button {

width: 0;

height: 0;

display: none;

}

::-webkit-scrollbar-thumb {

width: 7px;

background-color: #b4babf;

border-radius: 7px;

}

::-webkit-scrollbar {

width: 7px;

height: 7px;

}

::-webkit-scrollbar-track {

width: 15px;

}

::-webkit-scrollbar:hover {

background-color: transparent;

}

* {

cursor: url("http://cdn.mydearest.cn/blog/images/miku1.png"),auto!important

}

:active {

cursor: url("http://cdn.mydearest.cn/blog/images/miku2.png"),auto!important

}

a:hover {

cursor: url("http://cdn.mydearest.cn/blog/images/miku2.png"),auto!important

}

cosyer's Blog

Blog

JS

react组件实现按需加载

第一种:ReactTraining/react-router 介绍的基于 webpack, babel-plugin-syntax-dynamic-import, 和 react-loadable.

主要是利用了react-loadable这个高级组件,他是专门用来异步加载(也可以预加载)组件的。

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/code-splitting.md


第二种:SF网友介绍的Bundle组件配合webpack组件bundle-loader

bundle-loader效用其实和require.ensure()一样,把组件分片成单独的chunk,在Bundle组件中引入

https://segmentfault.com/a/1190000009539836

但是我尝试的时候发现总是报错说不要在import中引入webpack的loader。。。

然后我继续查,发现第三种实现

第三种:简书AlienZHOU介绍的同样基于create-react-app的方式,在Bundle组件中props入一个()=>import(‘path’)函数

http://www.jianshu.com/p/547aa7b92d8c

第四种,create-react-app文档给的react-router按需加载实现:用一个类Bundle组件的异步函数

https://serverless-stack.com/chapters/code-splitting-in-create-react-app.html

这种方式我试了下,确实能分片,但是讨论里有人指出性能上不如Bundle组件,那个人好像还是Create-react-app的主要贡献者

四种方式我都试过,期间。。这个过程略痛苦。。。不过结论是:第三种是目前我认为最好的,基于create-react-app,且实现最简单。

但是较大的项目,一般我们都会eject出来自己配置webpack啦,其实影响也不大。

本文结束感谢您的阅读

本文标题:react组件实现按需加载

文章作者:陈宇(cosyer)

发布时间:2018年08月15日 - 10:08

最后更新:2018年12月15日 - 13:12

原始链接:http://mydearest.cn/react组件实现按需加载.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

var clipboard = new Clipboard('.fa-clipboard');

clipboard.on('success', $(function(){

$(".fa-clipboard").click(function(){

swal({

title: "",

text: '复制成功',

timer: 500,

showConfirmButton: false

});

});

}));

坚持原创技术分享,您的支持将鼓励我继续创作!

陈宇(cosyer) WeChat Pay

WeChat Pay

陈宇(cosyer) Alipay

Alipay

css绘制几何图形

移动端web问题总结(长期更新)

if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {

window.Promise = null;

}

var GUEST = ['nick','mail','link'];

var guest = '';

guest = guest.split(',').filter(item=>{

return GUEST.indexOf(item)>-1;

});

new Valine({

av: AV,

el: '#comments' ,

appId: 'SKflNaQWS70153r2kOqgcGge-gzGzoHsz',

appKey: 'gE9ySnRyOkS4UNzYJ7GOCa56',

placeholder: '想说点什么 :)',

avatar: 'retro'

});

// Popup Window;

var isfetched = false;

var isXml = true;

// Search DB path;

var search_path = "search.json";

if (search_path.length === 0) {

search_path = "search.xml";

} else if (/json$/i.test(search_path)) {

isXml = false;

}

var path = "/" + search_path;

// monitor main search box;

var onPopupClose = function (e) {

$('.popup').hide();

$('#local-search-input').val('');

$('.search-result-list').remove();

$('#no-result').remove();

$(".local-search-pop-overlay").remove();

$('body').css('overflow', '');

}

function proceedsearch() {

$("body")

.append('

.css('overflow', 'hidden');

$('.search-popup-overlay').click(onPopupClose);

$('.popup').toggle();

var $localSearchInput = $('#local-search-input');

$localSearchInput.attr("autocapitalize", "none");

$localSearchInput.attr("autocorrect", "off");

$localSearchInput.focus();

}

// search function;

var searchFunc = function(path, search_id, content_id) {

'use strict';

// start loading animation

$("body")

.append('

' +

'

' +

'' +

'

' +

'

')

.css('overflow', 'hidden');

$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

$.ajax({

url: path,

dataType: isXml ? "xml" : "json",

async: true,

success: function(res) {

// get the contents from search data

isfetched = true;

$('.popup').detach().appendTo('.header-inner');

var datas = isXml ? $("entry", res).map(function() {

return {

title: $("title", this).text(),

content: $("content",this).text(),

url: $("url" , this).text()

};

}).get() : res;

var input = document.getElementById(search_id);

var resultContent = document.getElementById(content_id);

var inputEventFunction = function() {

var searchText = input.value.trim().toLowerCase();

var keywords = searchText.split(/[\s\-]+/);

if (keywords.length > 1) {

keywords.push(searchText);

}

var resultItems = [];

if (searchText.length > 0&&datas.length>0) {

// perform local searching

datas.forEach(function(data) {

var isMatch = false;

var hitCount = 0;

var searchTextCount = 0;

var title = data.title.trim();

var titleInLowerCase = title.toLowerCase();

var content = data.content&&data.content.trim().replace(/]+>/g,"");

var contentInLowerCase = content&&content.toLowerCase();

var articleUrl = decodeURIComponent(data.url);

var indexOfTitle = [];

var indexOfContent = [];

// only match articles with not empty titles

if(title != '') {

keywords.forEach(function(keyword) {

function getIndexByWord(word, text, caseSensitive) {

var wordLen = word.length;

if (wordLen === 0) {

return [];

}

var startPosition = 0, position = [], index = [];

if (!caseSensitive) {

text = text&&text.toLowerCase();

word = word&&word.toLowerCase();

}

while ((position = text&&text.indexOf(word, startPosition)) > -1) {

index.push({position: position, word: word});

startPosition = position + wordLen;

}

return index;

}

indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));

indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));

});

if (indexOfTitle.length > 0 || indexOfContent.length > 0) {

isMatch = true;

hitCount = indexOfTitle.length + indexOfContent.length;

}

}

// show search results

if (isMatch) {

// sort index by position of keyword

[indexOfTitle, indexOfContent].forEach(function (index) {

index.sort(function (itemLeft, itemRight) {

if (itemRight.position !== itemLeft.position) {

return itemRight.position - itemLeft.position;

} else {

return itemLeft.word.length - itemRight.word.length;

}

});

});

// merge hits into slices

function mergeIntoSlice(text, start, end, index) {

var item = index[index.length - 1];

var position = item.position;

var word = item.word;

var hits = [];

var searchTextCountInSlice = 0;

while (position + word.length <= end && index.length != 0) {

if (word === searchText) {

searchTextCountInSlice++;

}

hits.push({position: position, length: word.length});

var wordEnd = position + word.length;

// move to next position of hit

index.pop();

while (index.length != 0) {

item = index[index.length - 1];

position = item.position;

word = item.word;

if (wordEnd > position) {

index.pop();

} else {

break;

}

}

}

searchTextCount += searchTextCountInSlice;

return {

hits: hits,

start: start,

end: end,

searchTextCount: searchTextCountInSlice

};

}

var slicesOfTitle = [];

if (indexOfTitle.length != 0) {

slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));

}

var slicesOfContent = [];

while (indexOfContent.length != 0) {

var item = indexOfContent[indexOfContent.length - 1];

var position = item.position;

var word = item.word;

// cut out 100 characters

var start = position - 20;

var end = position + 80;

if(start < 0){

start = 0;

}

if (end < position + word.length) {

end = position + word.length;

}

if(end > content.length){

end = content.length;

}

slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));

}

// sort slices in content by search text's count and hits' count

slicesOfContent.sort(function (sliceLeft, sliceRight) {

if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {

return sliceRight.searchTextCount - sliceLeft.searchTextCount;

} else if (sliceLeft.hits.length !== sliceRight.hits.length) {

return sliceRight.hits.length - sliceLeft.hits.length;

} else {

return sliceLeft.start - sliceRight.start;

}

});

// select top N slices in content

var upperBound = parseInt('1');

if (upperBound >= 0) {

slicesOfContent = slicesOfContent.slice(0, upperBound);

}

// highlight title and content

function highlightKeyword(text, slice) {

var result = '';

var prevEnd = slice.start;

slice.hits.forEach(function (hit) {

result += text.substring(prevEnd, hit.position);

var end = hit.position + hit.length;

result += '' + text.substring(hit.position, end) + '';

prevEnd = end;

});

result += text.substring(prevEnd, slice.end);

return result;

}

var resultItem = '';

if (slicesOfTitle.length != 0) {

resultItem += "

" + highlightKeyword(title, slicesOfTitle[0]) + "";

} else {

resultItem += "

" + title + "";

}

slicesOfContent.forEach(function (slice) {

resultItem += "" +

"

" + highlightKeyword(content, slice) +

"...

" + "";

});

resultItem += "

";

resultItems.push({

item: resultItem,

searchTextCount: searchTextCount,

hitCount: hitCount,

id: resultItems.length

});

}

})

};

if (keywords.length === 1 && keywords[0] === "") {

resultContent.innerHTML = '

} else if (resultItems.length === 0) {

resultContent.innerHTML = '

} else {

resultItems.sort(function (resultLeft, resultRight) {

if (resultLeft.searchTextCount !== resultRight.searchTextCount) {

return resultRight.searchTextCount - resultLeft.searchTextCount;

} else if (resultLeft.hitCount !== resultRight.hitCount) {

return resultRight.hitCount - resultLeft.hitCount;

} else {

return resultRight.id - resultLeft.id;

}

});

var searchResultList = '

  • ';

resultItems.forEach(function (result) {

searchResultList += result.item;

})

searchResultList += "

";

resultContent.innerHTML = searchResultList;

}

}

if ('auto' === 'auto') {

input.addEventListener('input', inputEventFunction);

} else {

$('.search-icon').click(inputEventFunction);

input.addEventListener('keypress', function (event) {

if (event.keyCode === 13) {

inputEventFunction();

}

});

}

// remove loading animation

$(".local-search-pop-overlay").remove();

$('body').css('overflow', '');

proceedsearch();

}

});

}

// handle and trigger popup window;

$('.popup-trigger').click(function(e) {

e.stopPropagation();

if (isfetched === false) {

searchFunc(path, 'local-search-input', 'local-search-result');

} else {

proceedsearch();

};

});

$('.popup-btn-close').click(onPopupClose);

$('.popup').click(function(e){

e.stopPropagation();

});

$(document).on('keyup', function (event) {

var shouldDismissSearchPopup = event.which === 27 &&

$('.search-popup').is(':visible');

if (shouldDismissSearchPopup) {

onPopupClose();

}

});

function showTime(Counter) {

var query = new AV.Query(Counter);

var entries = [];

var $visitors = $(".leancloud_visitors");

$visitors.each(function () {

entries.push( $(this).attr("id").trim() );

});

query.containedIn('url', entries);

query.find()

.done(function (results) {

var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

if (results.length === 0) {

$visitors.find(COUNT_CONTAINER_REF).text(0);

return;

}

for (var i = 0; i < results.length; i++) {

var item = results[i];

var url = item.get('url');

var time = item.get('time');

var element = document.getElementById(url);

$(element).find(COUNT_CONTAINER_REF).text(time);

}

for(var i = 0; i < entries.length; i++) {

var url = entries[i];

var element = document.getElementById(url);

var countSpan = $(element).find(COUNT_CONTAINER_REF);

if( countSpan.text() == '') {

countSpan.text(0);

}

}

})

.fail(function (object, error) {

console.log("Error: " + error.code + " " + error.message);

});

}

function addCount(Counter) {

var $visitors = $(".leancloud_visitors");

var url = $visitors.attr('id').trim();

var title = $visitors.attr('data-flag-title').trim();

var query = new AV.Query(Counter);

query.equalTo("url", url);

query.find({

success: function(results) {

if (results.length > 0) {

var counter = results[0];

counter.fetchWhenSave(true);

counter.increment("time");

counter.save(null, {

success: function(counter) {

var $element = $(document.getElementById(url));

$element.find('.leancloud-visitors-count').text(counter.get('time'));

},

error: function(counter, error) {

console.log('Failed to save Visitor num, with error message: ' + error.message);

}

});

} else {

var newcounter = new Counter();

/* Set ACL */

var acl = new AV.ACL();

acl.setPublicReadAccess(true);

acl.setPublicWriteAccess(true);

newcounter.setACL(acl);

/* End Set ACL */

newcounter.set("title", title);

newcounter.set("url", url);

newcounter.set("time", 1);

newcounter.save(null, {

success: function(newcounter) {

var $element = $(document.getElementById(url));

$element.find('.leancloud-visitors-count').text(newcounter.get('time'));

},

error: function(newcounter, error) {

console.log('Failed to create');

}

});

}

},

error: function(error) {

console.log('Error:' + error.code + " " + error.message);

}

});

}

$(function() {

var Counter = AV.Object.extend("Counter");

if ($('.leancloud_visitors').length == 1) {

addCount(Counter);

} else if ($('.post-title-link').length > 1) {

showTime(Counter);

}

});

MathJax.Hub.Config({

tex2jax: {

inlineMath: [ ['$','$'], ["\\(","\\)"] ],

processEscapes: true,

skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']

}

});

MathJax.Hub.Queue(function() {

var all = MathJax.Hub.getAllJax(), i;

for (i=0; i < all.length; i += 1) {

all[i].SourceElement().parentNode.className += ' has-jax';

}

});

// 下雪

//(function($){$.fn.snow=function(options){var $flake=$('

//$.fn.snow({ minSize: 5, maxSize: 50, newOn: 1000, flakeColor: '#00F' });

// 点线连接

!function () { function o(w, v, i) { return w.getAttribute(v) || i } function j(i) { return document.getElementsByTagName(i) } function l() { var i = j("script"), w = i.length, v = i[w - 1]; return { l: w, z: o(v, "zIndex", -1), o: o(v, "opacity", 1), c: o(v, "color", "255, 255, 255"), n: o(v, "count", 99) } } function k() { r = u.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, n = u.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight } function b() { e.clearRect(0, 0, r, n); var w = [f].concat(t); var x, v, A, B, z, y; t.forEach(function (i) { i.x += i.xa, i.y += i.ya, i.xa *= i.x > r || i.x < 0 ? -1 : 1, i.ya *= i.y > n || i.y < 0 ? -1 : 1, e.fillRect(i.x - 0.5, i.y - 0.5, 1, 1); for (v = 0; v < w.length; v++) { x = w[v]; if (i !== x && null !== x.x && null !== x.y) { B = i.x - x.x, z = i.y - x.y, y = B * B + z * z; y < x.max && (x === f && y >= x.max / 2 && (i.x -= 0.03 * B, i.y -= 0.03 * z), A = (x.max - y) / x.max, e.beginPath(), e.lineWidth = A / 2, e.strokeStyle = "rgba(" + s.c + "," + (A + 0.2) + ")", e.moveTo(i.x, i.y), e.lineTo(x.x, x.y), e.stroke()) } } w.splice(w.indexOf(i), 1) }), m(b) } var u = document.createElement("canvas"), s = l(), c = "c_n" + s.l, e = u.getContext("2d"), r, n, m = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (i) { window.setTimeout(i, 1000 / 45) }, a = Math.random, f = { x: null, y: null, max: 20000 }; u.id = c; u.style.cssText = "position:fixed;top:0;left:0;z-index:" + s.z + ";opacity:" + s.o; j("body")[0].appendChild(u); k(), window.onresize = k; window.onmousemove = function (i) { i = i || window.event, f.x = i.clientX, f.y = i.clientY }, window.onmouseout = function () { f.x = null, f.y = null }; for (var t = [], p = 0; s.n > p; p++) { var h = a() * r, g = a() * n, q = 2 * a() - 1, d = 2 * a() - 1; t.push({ x: h, y: g, xa: q, ya: d, max: 6000 }) } setTimeout(function () { b() }, 100) }();

// 崩溃欺骗

var OriginTitle = document.title;

var titleTime;

document.addEventListener('visibilitychange', function () {

if (document.hidden) {

$('[rel="icon"]').attr('href', "/img/TEP.ico");

document.title = '╭(°A°`)╮ 页面崩溃啦 ~';

clearTimeout(titleTime);

}

else {

$('[rel="icon"]').attr('href', "/favicon.ico");

document.title = '(ฅ>ω

titleTime = setTimeout(function () {

document.title = OriginTitle;

}, 2000);

}

});

// 存活时间

var aliveList=document.getElementsByClassName("alive")

setInterval(function() {

var time = new Date();

// 程序计时的月从0开始取值后+1

//根据自己博客的创建时间更改数值

var t = "博客存活了"+Math.floor((+new Date - 1527868800000) / (1000 * 60 * 60 * 24)) + "天 " + time.getHours() + "小时"

+ time.getMinutes() + "分" + time.getSeconds() + "秒";

aliveList[0].innerHTML = t;

}, 1000);

// 统计页面加载时间

window.onload = function () {

var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;

console.log('Page load time is '+ loadTime);

}

.comments.no-post {

background: transparent;

}

.no-post.v *{

color: #ddd;

}

.v .vlist p {

margin: 12px 0;

}

.v .vbtn {

background: #fbfbfb;

padding: .3rem 1.2em;

border: 1px solid #dddddd75;

}

.no-post.v .vbtn {

background: #2222220a;

}

.no-post.v .vbtn:active, .no-post.v .vbtn:hover {

background-color: #fff;

}

.no-post.v .vwrap {

border: 1px solid #f0f0f036;;

}

.no-post.v a {

color: #ddd;

}

.v ul {

padding-left: 25px;

}

.v ul li {

list-style: disc;

padding: 2px 15px 0 0;

}

.v .vlist strong , .vinput.vpreview strong {

color: #87daff;

font-size: 108%;

}

.v .vlist .vcard .vhead .vsys {

background: #87daff17;

color: #aaa;

border: 1px solid #87daff1f;

padding: 1px 5px;

font-size: 12px;

line-height: 1.4;

}

.no-post.v .vlist .vcard .vhead .vsys{

background: #ededed1f;

color: #808080;

padding: 1px 5px;

font-size: 12px;

line-height: 1.4;

border: none;

}

.v .vlist .vcard .vcontent a {

color: #86dbff;

border-bottom-color: #86dbff99;

}

.v .vlist .vcard .vcontent a:hover {

color: #d7191a;

border-bottom-color: #222;

}

.no-post.v .vlist .vcard section {

border-bottom: 1px dashed #f5f5f55e;

}

.v .vwrap .vheader .vinput {

width: 33.33%;

border-bottom: 1px dashed #dedede45;

}

.no-post.v .vwrap .vheader .vinput::-webkit-input-placeholder {

color: #808080;

}

.no-post.v .vwrap .vheader .vinput:-ms-input-placeholder{ /* Internet Explorer 10-11 */

color: #808080;

}

.v .txt-right {

display: none;

}

.v .vlist .vcard .vcontent .code, .v .vlist .vcard .vcontent code, .v .vlist .vcard .vcontent pre , .vinput.vpreview code , .vinput.vpreview pre {

color: #005098fc;

background: #87daffb8;

border-radius: 4px;

box-shadow: 0 0 2px #87daff;

font-size: 90%;

padding: 2px 6px;

}

.v .vlist .vcard .vcontent img {

max-width: 18px;

display: inline-block;

}

.v .vlist .vcard .vcontent img{

max-width:18px;

display:inline-block

}

.v .vwrap .vheader .vinput:focus {

border-bottom: 1px solid #87daff;

}

.v .vlist .vcard .vcontent pre , .vinput.vpreview pre {

background: #87daff21;

border-radius: 4px;

box-shadow: 0 0 2px #ffffff33;

}

.v .vlist .vcard .vcontent pre code ,.vinput.vpreview pre code {

color: #87daff;

background: #87daff00;

border-radius: 4px;

box-shadow: 0 0 2px #87daff05;

}

.v .vlist .vcard .vcontent.expand:after {

color: #ff0000de;

font-size: 110%;

font-weight: bold;

background: #87daff38;

border-bottom-right-radius: 4px;

border-bottom-left-radius: 4px;

}

.comments.no-post .vlist .vcard .vcontent.expand:after {

color: #fff;

}

@media screen and (max-width: 414px) {

.v .vlist {

padding-left: 0;

}

}

.v .vlist .vcard .vcontent.expand:before {

background: linear-gradient(180deg,hsla(0, 0%, 100%, 0),hsla(199, 100%, 76%, 0.22));

background: -webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(199, 100%, 76%, 0.22));

}

一键复制

编辑

Web IDE

原始数据

按行查看

历史

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值