最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Dynamically loading JavaScript widget with data attributes - Stack Overflow

programmeradmin3浏览0评论

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

<script src='.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(".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>

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

<script src='http://domain./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./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>
Share Improve this question edited Jun 26, 2015 at 15:16 superphonic asked May 29, 2015 at 13:33 superphonicsuperphonic 8,0746 gold badges34 silver badges64 bronze badges 10
  • $("head").append("<script data-id='LFKkv' data-width='240'><\/script>").prop("src", 'http://domain./public/jsonp/widget.js'); – dandavis Commented Jun 24, 2015 at 20:58
  • @dandavis I'm afraid this doesn't do anything... – superphonic Commented Jun 25, 2015 at 8:23
  • @superphonic Can include js within widget.js where widget accesses data-* attributes of script element when loaded at Question ? – guest271314 Commented Jun 25, 2015 at 15:07
  • @guest271314 I am not sure what you just said, sorry. – superphonic Commented Jun 25, 2015 at 16:35
  • @superphonic Can portion of widget.js which accesses data-* attributes of script element appended to document ? – guest271314 Commented Jun 26, 2015 at 2:28
 |  Show 5 more ments

5 Answers 5

Reset to default 6 +100

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)
});

Use jQuery load() like

$(window).load(function() {
    $('<script/>').attr({
        'src': 'http://domain./public/jsonp/widget.js',
        'data-id': 'LFKkv',
        'data-width': '240'
    }).appendTo('body')
});
function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref) }   loadjscssfile("myscript.js", "js") //dynamically load and add this .js file loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

ok you should try this instead:

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

This is how you pass parameters in a url. You put ? and then start putting data=value&data2=value2 And it has to be properly html encoded.

Can you wrap your widget in a function, and use an event listener?

window.addEventListener('load', function() {

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

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

    var scriptTag = targetScripts[targetScripts.length - 1];

    console.log( scriptTag.dataset.width );

});
发布评论

评论列表(0)

  1. 暂无评论