Import javascript dynamically with jQuery?

浪子不回头ぞ 提交于 2019-12-11 07:19:51

问题


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


回答1:


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>



回答2:


You can do something like this...

var myOtherFramework = null;

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

And then reference it like...

myOtherFramework.funcName();



回答3:


The javascript you load, should itself already be using unique namespaces.



来源:https://stackoverflow.com/questions/996940/import-javascript-dynamically-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!