opencart变慢,magento学习
2022-11-02 11:07:24 - 米境通跨境电商
Opencart2.0和1.5.6版本并不是完全兼容的,如果你现在有正在运行的opencart站点,不建议你升级。
扯了一段题外话。如果你在本地安装opencart2.0站点试用的话,你会发现打开很慢,opencart2.0版本用了很多时髦技术,其中还包括GoogleFonts。我们知道国内把Google的IP地址都给墙了,所以,你没办法,你只能选择把字体下载到本地,或者调用国内的CDN,比如360。
文件位置:catalogview hemedefault emplatecommonheader.tpl
找到:
替换为:
如果你想进一步优化opencart的打开速度,不妨把opencart引入的JS类库等都换成CDN。
找到:
替换为:
!window.jQuery&&document.write('');
为了防止CDN宕机,(虽然这种情况极少见),我还是做了判断,在宕机的情况下调用本地的jQuery类库。
如果要对bootstrap的CDN引入也做此判断的话,就需要动态判断JS和CSS是否引入成功。
新建文件:catalogviewjavascriptcustom.js
//判断是否成功引入css文件
functionisCssLoaded(link){
try{
if(link.sheet&&link.sheet.cssRules.length>0)
returntrue;
elseif(link.styleSheet
&&link.styleSheet.cssText.length>0)
returntrue;
elseif(link.innerHTML
&&link.innerHTML.length>0)
returntrue;
}
catch(ex){
if(ex.name&&ex.name=='NS_ERROR_DOM_SECURITY_ERR')
returntrue;
}
returnfalse;
}
//动态引入CSS、JS文件
vardynamicLoading={
css:function(path){
if(!path||path.length===0){
thrownewError('argument"path"isrequired!');
}
varhead=document.getElementsByTagName('head')[0];
varlink=document.createElement('link');
link.href=path;
link.rel='stylesheet';
link.type='text/css';
head.appendChild(link);
},
js:function(path){
if(!path||path.length===0){
thrownewError('argument"path"isrequired!');
}
varhead=document.getElementsByTagName('head')[0];
varscript=document.createElement('script');
script.src=path;
script.type='text/javascript';
head.appendChild(script);
}
}
引入custom.js文件到header.tpl里,
再加入以下代码:
varisGoo=isCssLoaded("//fonts.googleapis.com/css?family=Open+Sans:400,400i,300,700");
//如果GoogleFonts无法加载,引入360的CDN类库
if(!isGoo){
dynamicLoading.css("http://fonts.useso.com/css?family=Open+Sans:300,400,600&subset=latin,latin-ext");
}
//Bootstrap加载失败,引入本地的类库文件
varisBootCss=isCssLoaded("https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css");
if(!isBootCss){
dynamicLoading.css("catalog/view/javascript/bootstrap/css/bootstrap.min.css");
}