Inserting A Self-Executing Script JavaScript/Shopify

389 Views Asked by At

I'm building an application for Shopify - the purpose is to insert a script tag. I need help writing the insertion code.

I'm following this advice to check if jQuery has been loaded, and then loading my code in the middle. Yet, it doesn't seem to be working. Here's the exact code:

(function(){

  var loadScript = function(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
      script.onreadystatechange = function(){
        if (script.readyState == "loaded" ||
          script.readyState == "complete"){
          script.onreadystatechange = null;
        callback();
      }
    };
    } else {  //Others
      script.onload = function(){
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  };

  // my actual jQuery code

  var myAppJavaScript = function($){
    var convert = $('.click-2-tweet-shopify');
    $.each(convert, function(index, item){
      var content = $(item).text().compact();
      $(item)
      .addClass('ui segment')
      .append('<a target=_blank class="pointer float-right"><i class="twitter icon"></i>Click2Tweet</a>')
      .children('a')
      .attr('href', "http://twitter.com/share?" + $.param({ text: content }));  
    });  

    // twitter code snippet

    !function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (!d.getElementById(id)) {
        js = d.createElement(s);
        js.id = id;
        js.src = "https://platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js, fjs);
      }
    }(document, "script", "twitter-wjs");
  };

  if ((typeof jQuery === 'undefined') || (parseFloat(jQuery.fn.jquery) < 1.7)) {
    loadScript('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', function(){
      jQuery191 = jQuery.noConflict(true);
      myAppJavaScript(jQuery191);
    });
  } else {
    myAppJavaScript(jQuery);
  }

});

Please imagine that the purpose of this script is to be standalone. If one were to add this to any page, it should work as is (since it loads jQuery initially). How should I adjust the code to work as intended?

1

There are 1 best solutions below

0
On BEST ANSWER

We always forget the little things sometimes! You forgot the 2nd I in your IIFE :)

(function(){
    //.....
    //All your code
    //.....
}()); // () --> this :)

-Updated fiddle-