通过外部js文件将jquery加上额外的脚本注入网页

时间:2011-10-06 20:05:23

标签: jquery

我试图通过外部js文件将两个js / jquery文件注入网页。

为了使它能够工作,我将需要注入一个jQuery框架(它在页面中不存在)和后续注入我自己的js文件。

为了使这项工作,我一直在尝试生成一个jquery注入器,但最终使用了一个由Karl Swedberg(http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet)

当你从文件中删除不需要的东西(至少我是这么认为)并根据我的需要调整它时,我得到:

(function() {
var el=document.createElement('div'),
b=document.getElementsByTagName('body')[0];
otherlib=false;
if(typeof jQuery!='undefined') {
    //msg='This page already using jQuery v'+jQuery.fn.jquery;
}
else if (typeof $=='function') {
    otherlib=true;
}

// more or less stolen form jquery core and adapted by paul irish
function getScript(url,secondaryScripts, success){
    var script=document.createElement('script');
    script.src=url;
    //if (secondaryScripts)
//          script.appendChild(document.createTextNode('var jQuery = jQuery.noConflict();'));
    var head=document.getElementsByTagName('head')[0],
    done=false;
    // Attach handlers for all browsers
    script.onload=script.onreadystatechange = function(){
        if ( !done && (!this.readyState
        || this.readyState == 'loaded'
        || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    }
    ;
    head.appendChild(script);
}

getScript('http://code.jquery.com/jquery-latest.min.js',false, function() {
    if (typeof jQuery=='undefined') {
        //msg='Sorry, but jQuery wasn\'t able to load';
    }
    else {
        if (otherlib) {
            //msg+=' and noConflict(). Use $jq(), not $().';
            $jq=jQuery.noConflict()

        }
    }
});

getScript('jquery-ui-1.8.16.custom.min.js', true, function() {});
getScript('script-20111006-1516.js', true, function() {});      

}
)();

但它没有工作,并且firebug报告没有定义jquery。这似乎是正确的,因为即使在这个似乎有用的脚本中我也无法执行任何jquery。

在我的外部文件中,包装:

(function($, 
})(jQuery);

因为我试图让我的脚本不与​​已经运行的任何东西发生冲突。但我也可能在这里做错了一些事情:)

希望有人能帮助我朝着正确的方向前进。

此致 丹尼斯

1 个答案:

答案 0 :(得分:1)

解决方案是在jquery完全加载后注入脚本。

相关问题