我一直在研究一个加载外部jQuery.js文件的bookmarklet项目,如下所示:
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文件时会触发的任何事件?)
谢谢!
答案 0 :(得分:3)
<script>
个元素有onload
个事件。
答案 1 :(得分: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;
答案 2 :(得分: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 );