Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically loading JavaScript widget with data attributes

Currently I have a widget which you insert somewhere on you page with the following

<script src='http://domain.com/public/jsonp/widget.js' data-id='LFKkv' data-width='240'></script>

I would like to load this dynamically after the page has loaded, I have tried jQuery $.getScript like below, which fails miserably:

$.getScript("http://domain.com/public/jsonp/widget.js' data-id='LFKkv' data-width='240'", function(data){ ... })

Because of the spaces on the URL between the data attributes I assume.

I could use ajax but I don't know how to pass data attributes via the jQuery ajax call? How do I dynamically load the above widget with data attributes intact?

EDIT: Including the relevant parts of my widget script so you can see how my widget grabs the data attributes:

    <script>

    var scriptName = "widget.js";
    TGW = window.jQuery.noConflict(true);

    var allScripts = document.getElementsByTagName('script');
    var targetScripts = [];

    for (var i in allScripts) {
        var name = allScripts[i].src
        if(name && name.indexOf(scriptName) > 0)
            targetScripts.push(allScripts[i]);
    }

    scriptTag = targetScripts[targetScripts.length - 1];

    // Getting the data attributes here
    jScript = TGW(scriptTag);
    id = jScript.data("id");
    widget_width = jScript.data("width");
   </script>
like image 723
superphonic Avatar asked May 29 '15 13:05

superphonic


1 Answers

Try passing options object to an "init" function which loads widget,js, set options on widget at success callback of "init" function

TGW = window.jQuery.noConflict(true);
function initWidget (options) {
  return TGW.ajax({
    url: url,
    dataType: "script"
  })
  .then(function(script) {
    // if `TGW.widgetName()` requires several seconds to load,
    // try adding adding `setTimeout` or `.delay` to wait
    // until `TGW.widgetName` defined before returning `TGW.widgetName`
    return options && TGW.widgetName 
           ? TGW.widgetName(options) 
           : TGW.widgetName(/* defaults?, are `id`, `width` required? */);
  });
};

initWidget({"id":"LFKkv", "width":"240"})
.then(function(widget) {
  console.log(widget)
});
like image 195
guest271314 Avatar answered Sep 17 '22 16:09

guest271314