Javascript Younow onLoad(带greasemonkey)

Javascript Younow onLoad(带greasemonkey),javascript,onload,Javascript,Onload,加载younow网站时,消息框“开始”会弹出两次-我怎样才能解决这个问题 // ==UserScript== // @name test // @include https://www.younow.com/* // @version 1 // @grant none // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js // ==/UserScript==

加载younow网站时,消息框“开始”会弹出两次-我怎样才能解决这个问题

// ==UserScript==
// @name        test
// @include   https://www.younow.com/*
// @version     1
// @grant       none
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
// ==/UserScript==
$(document).ready(function() { 
alert("Start");
});

警报
在该网站上以这种方式运行,可能是因为呼叫后重新加载,但对于我来说,有一个前缀就可以了

$(document).ready(function() { 
  $('body').prepend("toto"); // your code here
});
另外,您不需要使用ready函数,而是在正确的时间启动脚本

但问题是:

  • 我想您希望在加载所有ajax元素时完成自己的工作。因此,最好的方法是观察dom
  • 由于web站点在单击时使用AJAX请求更改当前页面,并且
    hashchange
    事件不起作用,因此我使用一些技巧来监听任何页面更改
  • 使用此脚本,您可以使用
    警报
    功能:

    // ==UserScript==
    // @name        test
    // @include   https://www.younow.com/*
    // @version     1
    // @grant       none
    // @require https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js
    // ==/UserScript==
    
    var observer = null;
    initObserver();
    
    function initObserver()
    {
      observer = new MutationObserver(onMutation);
      observer.observe(document,
      {
        childList: true, // report added/removed nodes
        subtree: true,   // observe any descendant elements
      });
    }
    
    $(window).on('hashchange', function(e)
    {
         initObserver();
    });
    
    intervalMutation = setInterval(onMutation.bind(null, null), 1000);
    
    function locationObserver()
    {
      var oldLocation = location.href;
       setInterval(function() {
            if(location.href != oldLocation) {
                 onMutation(null);
                 oldLocation = location.href
            }
        }, 1000); // check every second
    }
    locationObserver();
    
    function onMutation(mutations)
    {
      // Check if this class exits:
      if($('.trending-now').length ||
         $('.ynicon ynicon-chat').length ||
         $('.trending_title').length ||
         $('.trending-tags-list').length)
      {
         // Disconnect the observer:
         observer.disconnect();
         // Clear the interval :
         clearInterval(intervalMutation);
         // Call your code:
         pageReady();
      }
    }
    
    function pageReady()
    {
      // your code here:
      alert('start');
    }