简体   繁体   中英

How can I rewrite this jQuery code into Javascript?

I'm using a WordPress theme that only has about 10 lines of jQuery, yet it's using the 90kb jQuery file. I want to change this jQuery code to Javascript, but I'm not very good at Javascript:

jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
  $href = jQuery(this).attr('href');
  $contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
    $contentArea.fadeTo('fast', 1);
  });
  return false;
});


var $tabbed_area = jQuery('div#tabbed');
if ($tabbed_area.length) {
  $tabbed_area.tabs({
    fx: {
      opacity: 'toggle'
    }
  });
};

Thanks in advance!

Personally I'd persist with jQuery. Although there is "only about 10 lines jQuery" what it is doing is quite substantial. By the time you have recreated a lot of what jQuery is providing you here you will have a fairly decent slab of javaScript to debug and maintain. That is the beauty of jQuery, to quote their tag line "write less, do more" Remember with jQuery you are eliminating a lot of annoying cross browser quirks.

Edit: See tbranyen's answer for a practical example of why jQuery is worth it

Use a CDN version of jQuery, like Google's and you will be using jQuery that your uses may already have cached and therefore does not have to be downloaded again. jQuery UI can also be served in the same way. See this article: http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/

EDIT

Reading your question further "I'm not very good at javaScript" is all the more reason to stick with jQuery. Let it do all the heaving lifting for you. HOWEVER don't use jQuery as an excuse not to learn more about javaScript, the more you learn about javaScript the more you will be able to get out of jQuery.

My solution is fragmented, its not complete, and I do not expect points for this answer. This was me taking a stab at replicating jQuery's code in vanilla JS, purely as scientific justice to your question. I consider myself good at JavaScript, but even I know my limitations and time constraints. I only have one life on this planet and its honestly not worth my time to write out a tabs plugin and animation for your Wordpress site.

Just take a look at the code difference. If you're really scared about people downloading, you should ask yourself what makes your site so much different than the thousands/millions? of other sites that are visited by millions of people?

Writing this stuff is tedious, that's why if I have to do these things, I use jQuery. However , lets say you don't care about older browser support. You didn't mention that, I have a solution at the very bottom that does more, but WILL not work with older browsers or work period for that matter.

The original

Very little code to do immensely complicated stuff.

jQuery('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a').live("click", function () {
  $href = jQuery(this).attr('href');
  $contentArea.fadeTo('fast', 0.2).load($href + ' #main-area', function () {
    $contentArea.fadeTo('fast', 1);
  });
  return false;
});

Attempting to write from scratch

// Not even close to finished solution
(function(window, document) {
  var tabbed = document.getElementById('tabbed');

  // Semi-normalized event handling, not even a fraction as good as jQuery's
  function attachEvent(node, type, callback) {
    if(node.attachEvent) {
      return node.attachEvent('on'+type, function() {
        callback.apply(window.event.target, arguments);
      });
    }

    return node.addEventListener(type, function(e) {
      callback.apply(e.target, arguments);
    }, true);
  }

  // Semi-delegation again, not even a fraction of what jQuery offers
  attachEvent(document, 'click', function(e) {
    var href = this.href;
    var body = document.body;
    var elements = [];
    var slice = [].slice;
    var concat = elements.concat;

    // This is just the start of what it would take to emulate what jQuery is doing to match all those items
    // Without a reliable selector engine like querySelectorAll (not even that reliable) you'd need to match.
    elements = concat(slice.call(body.getElementById('main-tabbed-area').getElementsByTagName('a')));
    elements = concat(slice.call(body.getElementsByTagName('...');

    // Not even going to attempt fading
    // jQuery again does all this
  });

  if(tabbed && tabbed.tagName === 'div') {
    // No idea what tabs is? A plugin? Good luck!
  }

})(this, this.document);

Code is slightly more modern... but still jeesh look at all that code

function xhr(url, callback) {
  var request = new window.XMLHttpRequest();
  request.open('GET', url, true);
  request.onreadystatechange = function(e) {
    if(e.readyState === 4) {
      callback(e.responseXML);
    }
  };
  request.send(null);
}

// No idea what contentArea is
var contentArea = ...???;

(function(window, document) {
  var tabbed = document.getElementsById('tabbed');

  document.addEventListener('click', function(e) {
    var href;
    var elements = document.querySelectorAll('body #main-tabbed-area a, body .wp-pagenavi a, body .pagination a');
    var match = false;

    elements.forEach(function(element) {
      if(this === element) {
        match = true;
      }
    });

    if(match) {
      href = e.target.href;

      // Some CSS3 class that does a fade out
      contentArea.classList.add('fadeOut');

      xhr(href, function(data) {
        var data = data.getElementById('main-area').innerHTML;
        contentArea.innerHTML = data;

        contentArea.classList.remove('fadeOut');

        // Some CSS3 class that does a fade in
        contentArea.classList.add('fadeIn');
      });

      return false;
    }
  }, true);

  if(tabbed && tabbed.tagName === 'div') {
    // Still no idea what tabs is? A plugin? Good luck!
  }
})(this, this.document);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM