简体   繁体   中英

Import javascript dynamically with jQuery?

I'm trying to setup a widget framework using jQuery, so I need to import java script by parsing the widget's xhtml and including in the framework page. The problem is that this may lead to pollution of the namespace. Is it possible to load java script into a namespace at runtime?

Perhaps there is some better method that I'm overlooking?

Thanks, Pete

You can do something like this...

var myOtherFramework = null;

$.get("myScript.js", function(data) {
  myOtherFramework = eval("(" + data + ")");
});

And then reference it like...

myOtherFramework.funcName();

AS Josh Stodola mentioned creating the variable at runtime isn't the problem

var holdsWidgetUUID = "widgetUUIDValue";
eval(holdsWidgetUUID + "= (" + data + ")");
alert(eval(holdsWidgetUUID));

Or if you prefer

var UUID = "widgetUUID";
var holdsWidgetUUID = "widgetUUIDValue";
window["widgets"] = new Array();
window["widgets"][holdsWidgetUUID] = data;
alert(window["widgets"][holdsWidgetUUID]);

The problem is getting the loaded javascript to work an be callable like dynamicvariablename.methodname()

I have a working solution if you force a certain coding practice upon the included javascript. Maybe this gets you in the right direction.

This is a widgets javascript (works.js). Notive that it's a javascript "class" with internally defined fields and methods. Which by itself keeps namespace pollution low and allows us the achieve the desired calling form x.getInfo()

function () {
    this.type = 1;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' widget';
    };
}

And this is the file which includes it at runtime in a namespace

<html>
<head>
  <title>Widget Magic?</title>
  <script type='text/javascript' src='jquery.js'></script>
  <script type='text/javascript'>
    var UUID = "widgetUUID";
    var holdsWidgetUUID = "widgetUUIDValue";
    window["widgets"] = new Array();
    $.get("works.js", function(data) {
      window["widgets"][holdsWidgetUUID] = eval("(" + data + ")");
      $(document).ready(function() {
        window["widgets"][holdsWidgetUUID] = new (window["widgets"][holdsWidgetUUID])();
        alert(window["widgets"][holdsWidgetUUID].color);
        alert(window["widgets"][holdsWidgetUUID].getInfo());
      });
    });
  </script>
</head>
<body>
  <p>Just some stuff</p>
</body>
</html>

您加载的javascript本身应该已经在使用唯一的名称空间。

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