我在网上找到了一些代码,可以帮助我向客户提供小部件。我对下面完整代码的理解是,它首先检测是否存在 jQuery,否则会加载它。作为我的小部件的一部分,我还想确保加载fancybox,因为我基本上提供了一个按钮,onClicks 在fancybox 中加载一个iframe。
感兴趣的特定领域是.getScript
给我一个错误Unexpected token .
。我知道这jQuery
已经加载,因为.getJSON
下面的作品。
代码:
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5");
$.getScript(fancyboxScript);
/******* Load HTML *******/
var jsonp_url = widgetURL + "widgetCall.php?callback=?";
$.getJSON(jsonp_url,'merchantID='+merchantID, function(data) {
$('#widget-container').html(data.html);
});
完整代码如下:
(function() {
// Localize jQuery variable
var jQuery;
var widgetURL = "http://...mywidgetURL/...";
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: widgetURL + "myCSS.css"
});
css_link.appendTo('head');
/******* Load FANCYBOX *******/
var fancy_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: widgetURL + "fancybox/source/jquery.fancybox.css?v=2.1.5",
media: "screen"
});
fancy_link.appendTo('head');
var fancy2_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: widgetURL + "fancybox/source/helpers/jquery.fancybox-thumbs.css?v=1.0.7",
media: "screen"
});
fancy2_link.appendTo('head');
var fancyboxScript = widgetURL + "fancybox/source/jquery.fancybox.pack.js?v=2.1.5");
$.getScript(fancyboxScript);
/******* Load HTML *******/
var jsonp_url = widgetURL + "widgetCall.php?callback=?";
$.getJSON(jsonp_url,'merchantID='+merchantID, function(data) {
$('#widget-container').html(data.html);
});
});
}
})(); // We call our anonymous function immediately