1

我一直在研究一个加载外部 jQuery.js 文件的书签项目,如下所示:

jq_script = document.createElement('SCRIPT');
jq_script.type = 'text/javascript';
jq_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js';
document.getElementsByTagName('head')[0].appendChild(jq_script);

但是当我在此之后尝试使用 jQuery 时,我收到:

Uncaught ReferenceError: jQuery is not defined

在 chrome JS 控制台上。

加载单个 dom 实例时是否会调用任何“事件”?(或者像这样加载外部 JS 文件时触发的任何事件?)

谢谢!

4

3 回答 3

3

<script>元素有一个onload事件。

于 2012-07-12T05:41:40.517 回答
0

你可以这样做

function loadScript()
{
 jq_script = document.createElement('SCRIPT');
 jq_script.type = 'text/javascript';
 jq_script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js';
 document.getElementsByTagName('head')[0].appendChild(jq_script);
}

window.onload = loadScript;
于 2012-07-12T05:43:55.983 回答
0

更新:使用下面的最新 jquery 代码。

jQuery 的getScript以下列方式处理它。你可以把你的功能放在里面if(!isAbort)

script = document.createElement( "script" );

script.async = "async";

if ( s.scriptCharset ) {
    script.charset = s.scriptCharset;
}

script.src = s.url;

// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {

    if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

        // Handle memory leak in IE
        script.onload = script.onreadystatechange = null;

        // Remove the script
        if ( head && script.parentNode ) {
            head.removeChild( script );
        }

        // Dereference the script
        script = undefined;

        // Callback if not abort
        if ( !isAbort ) {
            //**Do your stuff here**
        }
    }
};
// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
于 2012-07-12T05:46:20.593 回答