uniapp开发与js原生开发的其一不同之处在于,前者是SPA单页面开发,每个项目中只有一个index.html文件,所谓的页面跳转本质来说是不停重写当前页面来与用户进行交互。原生开发是多个页面进行页面间的跳转,像在script引入外部文件就更加方便高效。
接入广告的不同方式
原生插入banner广告
了解了uniapp开发与js原生开发的不同,首先我们先从轻松的原生来实现广告功能。正常的html文件,插入广告可以直接在head中写入
<!-- 加载GPT的库,该库完全加载后,便会处理 googletag 对象中已加入队列的所有命令。 -->
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
window.googletag=window.googletag||{
cmd:[]};
googletag.cmd.push(function(){
googletag.defineSlot(‘不同广告唯一的插槽内容’).addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.pubads().collapseEmptyDivs();
googletag.enableServices();
});
</script>
然后在需要插入广告的部分在body中写入
<div id='广告的ID' style='不同广告的尺寸,一般banner广告位的尺寸为:min-width:300px;min-height:250px;'>
<script>
googletag.cmd.push(function(){
googletag.display('广告的ID');});
</script>
</div>
到此,在html文件中就可以插入不同尺寸的banner广告了。
原生插入插屏广告
插屏广告与banner广告有所不同,因为插屏广告是在页面跳转的时候展示,所以不需要盒子来让其填充,插屏广告自动全屏填充展示。所以直接在head中放入:
<!-- 加载GPT的库,该库完全加载后,便会处理 googletag 对象中已加入队列的所有命令。 -->
<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
window.googletag=window.googletag||{
cmd:[]};
googletag.cmd.push(function(){
var slot=googletag.defineOutOfPageSlot('广告唯一插口标识',
googletag.enums.OutOfPageFormat.INTERSTITIAL);
//Slot returns null if the page or device doesnot support interstitials
//页面和设备不支持插页,slot返回null
if (slot) slot.addService(googletag.pubads());
googletag.enableServices();
//Consider delaying until first div on page
//延迟到第一个页面中第一个盒子加载出来
googletag.display(slot);
});
</script>
放在跳转页面中,在页面发生跳转时,插页广告可以自动插入。
SPA插入banner广告
声明:作者也是探索出来的笨办法,实现功能为主,肯定有更高效简洁,读起来赏心悦目的代码可以展示广告,欢迎指正。
由于SPA的页面切换是局部刷新而不是整体刷新,Vue Templates中是不允许出现Script标签的。虽然我们可以通过type来规避这个报错:type=“application/javascript”,但这并不能彻底解决问题。当你把script标签写在Vue templates中时,因为Vue会根据数据