Sticky 通过在无限滚动中更改内容URL刷新粘性移动排行榜广告槽

Sticky 通过在无限滚动中更改内容URL刷新粘性移动排行榜广告槽,sticky,slot,Sticky,Slot,当URL在无限滚动中更改时,我想刷新粘性移动排行榜。你认为最好的方式是什么?如果你有任何建议,请告诉我 class DFPAds { constructor() { this.slots = []; this.onScroll = throttle(this.loopAds, 300); this.addEvents(); this.createAdObject = this.createAdObject.bind(this); this.creat

当URL在无限滚动中更改时,我想刷新粘性移动排行榜。你认为最好的方式是什么?如果你有任何建议,请告诉我

class DFPAds {
  constructor() {
    this.slots = [];
    this.onScroll = throttle(this.loopAds, 300);
    this.addEvents();

    this.createAdObject = this.createAdObject.bind(this);
    this.createSlotForAd = this.createSlotForAd.bind(this);
    this.displayAd = this.displayAd.bind(this);
  }

  static get() {
    return DFPAds._instance;
  }

  static set() {
    if (!DFPAds._instance) {
      DFPAds._instance = new DFPAds();
      return DFPAds._instance;
    } else {
      throw new Error("DFPAds: instance already initialized");
    }
  }

  addEvents() {
    window.addEventListener("scroll", e => this.onScroll());
  }

  loopAds() {
    this.slots.map(slot => this.displayAd(slot));
  }

  createAdObject(ad) {     
    let id = ad.id;
    let attributes = getDataSet(ad);    
    let sizes = JSON.parse(attributes.sizes);
    let sizeMapping;

    if (attributes.sizemapping) {
      attributes.sizemapping.length
        ? (sizeMapping = JSON.parse(attributes.sizemapping))
        : (sizeMapping = null);
    }

    attributes.id = id;
    attributes.sizes = sizes;
    attributes.sizemapping = sizeMapping;

    return attributes;
  }


  createSlotForAd(adObject) {
    let {
      id,
      adtype,
      position,
      slotname,
      sizes,
      sizemapping,
      shouldlazyload,
      pagenumber,
      pageid
    } = adObject;

    googletag.cmd.push(() => {
      let slot = googletag.defineSlot(slotname, sizes, id);

      if(position){
        slot.setTargeting("position", position);
      }
      if(pagenumber){
        slot.setTargeting("pagenumber", pagenumber);
      }

      if(pageid){
        slot.setTargeting("PageID", pageid)   
      }

      if (sizemapping) {
        let mapping = googletag.sizeMapping();

        sizemapping.map(size => {
          mapping.addSize(size[0], size[1])
        });

        slot.defineSizeMapping(mapping.build());
      }

      slot.addService(googletag.pubads());
      googletag.display(id);

      shouldlazyload
        ? this.slots.push({ slot: slot, id: id })
        : googletag.pubads().refresh([slot]);
        console.log("SlotTop", slot)
    });
  }

  displayAd(slot) {
    console.log("Slottwo", slot)
    let item = document.getElementById(slot.id);
    if (item) {
      let parent = item.parentElement;
      let index = this.slots.indexOf(slot);
      let parentDimensions = parent.getBoundingClientRect();

      if (
        (parentDimensions.top - 300) < window.innerHeight &&
        parentDimensions.top + 150 > 0 &&
        parent.offsetParent != null
      ) {
        googletag.cmd.push(function() {
          googletag.pubads().refresh([slot.slot]);
        });
        this.slots.splice(index, 1);
      }
    }
  }


  setUpAdSlots(context = document) {
    let ads = [].slice.call(context.getElementsByClassName("Ad-data"));
    if (ads.length) {
      ads.map(ad => compose(this.createSlotForAd, this.createAdObject)(ad));
    }
  }
}

export default DFPAds;
class-dfpad{
构造函数(){
this.slots=[];
this.onScroll=油门(this.loopAds,300);
这个。addEvents();
this.createAdObject=this.createAdObject.bind(this);
this.createSlotForAd=this.createSlotForAd.bind(this);
this.displayAd=this.displayAd.bind(this);
}
静态get(){
返回DFPAds.\u实例;
}
静态集(){
如果(!DFPAds.\u实例){
DFPAds._实例=新DFPAds();
返回DFPAds.\u实例;
}否则{
抛出新错误(“DFPAds:实例已初始化”);
}
}
addEvents(){
addEventListener(“scroll”,e=>this.onScroll());
}
loopAds(){
this.slots.map(slot=>this.displayAd(slot));
}
创建对象(ad){
设id=ad.id;
let attributes=getDataSet(ad);
让size=JSON.parse(attributes.size);
让大小映射;
if(attributes.sizemapping){
attributes.sizemapping.length
?(sizeMapping=JSON.parse(attributes.sizeMapping))
:(sizeMapping=null);
}
attributes.id=id;
attributes.size=大小;
attributes.sizemapping=sizemapping;
返回属性;
}
createSlotForAd(adObject){
让{
身份证件
adtype,
立场,,
slotname,
尺寸,
尺寸映射,
应该是蓝色的,
页码,
页面ID
}=对象;
googletag.cmd.push(()=>{
让slot=googletag.defineSlot(slotname,size,id);
如果(职位){
插槽设置目标(“位置”,位置);
}
如果(页码){
slot.setTargeting(“页码”,页码);
}
如果(页面ID){
slot.setTargeting(“PageID”,PageID)
}
if(尺寸映射){
让mapping=googletag.sizeMapping();
sizemapping.map(大小=>{
mapping.addSize(大小[0],大小[1])
});
slot.defineSizeMapping(mapping.build());
}
slot.addService(googletag.pubads());
googletag.display(id);
阿兹洛德酒店
?this.slots.push({slot:slot,id:id})
:googletag.pubads().refresh([slot]);
console.log(“SlotTop”,slot)
});
}
显示广告(插槽){
console.log(“Slottwo”,slot)
让item=document.getElementById(slot.id);
如果(项目){
让parent=item.parentElement;
设index=this.slots.indexOf(slot);
让parentDimensions=parent.getBoundingClientRect();
如果(
(parentDimensions.top-300)0&&
parent.offsetParent!=null
) {
googletag.cmd.push(函数(){
googletag.pubads().refresh([slot.slot]);
});
这是插槽拼接(索引1);
}
}
}
setUpAdSlots(上下文=文档){
让ads=[].slice.call(context.getElementsByClassName(“Ad数据”));
如果(广告长度){
ads.map(ad=>compose(this.createSlotForAd,this.createAdObject)(ad));
}
}
}
导出默认DFPAD;
这是我的无限滚动代码:

export default class InfiniteScroll {
    constructor() {
        this._end = document.getElementById('InfiniteScroll-End');
        this._container = document.getElementById('InfiniteScroll-Container');
            if(!this._end || !this._container)
                return;

        this._articles = { };
        this._triggeredArticles = [];
        this._currentArticle = '';
        this._apiUrl = '';
        this._count = 1;
        this._timedOut = false;
        this._loading = false;
        this._ended = false;
        this._viewedParameter = "&alreadyViewedContentIds=";
        this._articleSelector = "InfiniteScroll-Article-";
        this._articleClass = "Article-Container";

        this.setStartData();
        this.onScroll = throttle(this.eventScroll, 200);
        this.addEvents();
    }

    addEvents(){
        setTimeout(()=>{
            window.addEventListener('scroll', (e) => this.onScroll() );
        }, 2000);
    }

    addToStore(article){
        this._articles["a" + article.id] = article;
    }

    addToTriggeredArticles(id){
        this._triggeredArticles.push(id);
    }

    getRequestUrl(){
        return this._apiUrl + this._viewedParameter + Object.keys(this._articles).map(key => this._articles[key].id).join();
    }

    getLastArticle(){
        return this._articles[Object.keys(this._articles)[Object.keys(this._articles).length-1]];
    }

    setStartData() {
        let dataset = getDataSet(this._container);
        if(dataset.hasOwnProperty('apiurl')){
            let article = Article.get();
            if(article){
                this._apiUrl = dataset.apiurl;
                this._currentArticle = "a" + article.id;

                this.addToStore(article);
            }else{
                throw(new Error('Infinite Scroll: Article not initialized.'));
            }
        }else{
            throw(new Error('Infinite Scroll: Start object missing "apiurl" property.'));
        }
    }

    eventScroll() {
            if(this.isApproachingNext()){
                this.requestNextArticle();
            }

            if(!this.isMainArticle(this._articles[this._currentArticle].node)){
                this.updateCurrentArticle();
            }
    }

    eventRequestSuccess(data){
        this._loading = false;
        if(data != ''){
            if(data.hasOwnProperty('Id') && data.hasOwnProperty('Html') && data.hasOwnProperty('Url')){
                this.incrementCount();
                let node = document.createElement('div');
                node.id = this._articleSelector + data.Id;
                node.innerHTML = data.Html;
                node.className = this._articleClass;
                this._container.appendChild(node);

                this.initArticleUpNext({
                    img: data.Img, 
                    title: data.ArticleTitle, 
                    category: data.Category, 
                    target: node.id 
                });

                this.addToStore(
                    new Article({
                        id: data.Id, 
                        node: node, 
                        url: data.Url, 
                        title: data.Title, 
                        count: this._count,
                        nielsenProps: {
                            section: data.NeilsenSection,
                            sega: data.NeilsenSegmentA,
                            segb: data.NeilsenSegmentB,
                            segc: data.NeilsenSegmentC
                        }
                    })
                );
            }else{
                this._ended = true;
                throw(new Error('Infinite Scroll: Response does not have an ID, Url and HTML property'));
            }
        }else{
            this._ended = true;
            throw(new Error('Infinite Scroll: No new article was received.'));
        }
    }

    eventRequestError(response){
        this._loading = false;
        this._ended = true;
        throw(new Error("Infinite Scroll: New article request failed."));
    }

    requestNextArticle(){
        if(!this._loading){
            this._loading = true;
            return API.requestJSON(this.getRequestUrl())
                .then(
                    (response)=>{this.eventRequestSuccess(response)},
                    (response)=>{this.eventRequestError(response)}
                );
        }
    }


    triggerViewEvent(article){
        if(article.count > 1 && !this.isAlreadyTriggeredArticle(article.id)){
            this.addToTriggeredArticles(article.id);
            Tracker.pushView(article.url, article.count);

            if(isFeatureEnabled('Nielsen') && Nielsen.get()){
                Nielsen.get().eventInfiniteScroll({
                    id: article.id,
                    url: article.url,
                    section: article.nielsenProps.section,
                    sega: article.nielsenProps.sega,
                    segb: article.nielsenProps.segb,
                    segc: article.nielsenProps.segc
                });
                NielsenV60.trackEvent(article.title);
            }
        }
    }

    updateCurrentArticle(){
        Object.keys(this._articles).map( key => {
            if(this._currentArticle !== key && this.isMainArticle(this._articles[key].node)){
                this._currentArticle = key;
                this.updateUrl(this._articles[key]);
                this.triggerViewEvent(this._articles[key]);
            }
        }); 
    }

    updateUrl(article){
        try{
            if(history.replaceState){
                if(window.location.pathname !== article.url){
                    history.replaceState('', article.title, article.url);
                }
            }
        }catch(e){}
    }

    incrementCount(){
        this._count = this._count + 1;
    }

    initArticleUpNext(data){
        this.getLastArticle().initUpNext(data);
    }

    isApproachingNext(){
        return window.pageYOffset  > this._end.offsetTop - (window.innerHeight * 2) && !this._ended && this._end.offsetTop >= 100;
    }

    isMainArticle(node){
        if(node.getBoundingClientRect){
            return (node.getBoundingClientRect().top < 80 && node.getBoundingClientRect().bottom > 70);
        }else{
            return false;
        }
    }

    isAlreadyTriggeredArticle(id){
        return this._triggeredArticles.indexOf(id) > -1;
    }


}
导出默认类{
构造函数(){
this._end=document.getElementById('InfiniteScroll-end');
这个._container=document.getElementById('InfiniteScroll-container');
如果(!this.| | |!this.|容器)
返回;
这._articles={};
这个._triggeredArticles=[];
本._currentArticle='';
这是._apirl='';
这个._count=1;
这是.\u timedOut=false;
这是错误的;
这个。_end=false;
此._viewedParameter=“&AlreadyViewedContentId=“”;
这个._articleSelector=“无限滚动物品-”;
这个.\u articleClass=“物品容器”;
这个.setStartData();
this.onScroll=油门(this.eventScroll,200);
这个。addEvents();
}
addEvents(){
设置超时(()=>{
window.addEventListener('scroll',(e)=>this.onScroll());
}, 2000);
}
addToStore(文章){
本._条款[“a”+article.id]=条款;
}
AddToTriggerDarticles(id){
此._triggeredArticles.push(id);
}
getRequestUrl(){
返回此。_apiUrl+this。_viewedParameter+Object.keys(this.\u articles).map(key=>this.\u articles[key].id).join();
}
getLastArticle(){
返回此._articles[Object.keys(this._articles)[Object.keys(this._articles).length-1];
}
setStartData(){
让dataset=getDataSet(此.\u容器);
if(dataset.hasOwnProperty('apiurl')){
让article=article.get();
国际单项体育联合会(第条){
这是.\u apirl=dataset.apirl;
本文件。_currentArticle=“a”+article.id;
本.addToStore(文章);
}否则{
抛出(新错误('无限滚动:文章未初始化');
}
}否则{
抛出(新错误('Infinite Scroll:Start对象缺少“APIRL”属性)。);
}
}
eventScroll(){
if(this.isApproachingNext()){
this.requestNextArticle();
}
if(!this.isMainArticle(this.\u articles[this.\u currentArticle].node)){
this.updateCurrentArticle();
}
}
eventRequestSuccess(数据){
这是错误的;
如果(数据!=''){
if(data.hasOwnProperty('Id')&&data.hasOwnProperty('Html')&&data.hasOwnProperty('Url')){
这是.incrementCount();
让节点=document.createElement('div');
node.id=这个。_articleSelector+data.id;
node.innerHTML=data.Html;
node.className=这个;
此.\u container.append