Keep from loading the same javascript more than once - javascript

I want to prevent my system from loading the same script more than once, because different modules can be combined and I use third party libraries that I don't want to manipulate.
Has anyone done this before?

How about RequireJS? Seems to be what you're looking for.

As the libraries such as Require JS didn't solve my problems, I made my own solution, which I'm posting below.
My system is also made by different modules. In the main module, I have a loader for the dependencies of all the modules (php, js and css files). After the dependencies have been loaded, the app triggers an event and sets a global variable which prevents double inclusion of files.
Hope it helps. If you have any doubts, just let me know.
The code:
//Main
var main = {
init: function(){
//Dependencies to load (php, js or css)
var deps = [
'/helpers/edit/v/edit.php',
'/helpers/edit/css/edit.css',
'/helpers/validate/js/jquery.validate.js,messages_pt_BR.js'
];
//Load initial pack
if (!window.editReady){
//Load dependencies
this.load('edit',deps);
//Bind loaded event
$('body').on('editReady',function(){
//Set editLoaded to avoid double ajax requests
window.editReady = true;
//Do whatever you need after it's loaded
});
}
},
//Load external resources
load: function(name,data_urls){
var url, ext;
var len = data_urls.length;
var i = 0;
$(data_urls).each(function(){
//Get proper file
$.get(this, function(data) {
url = this.url;
ext = url.split('.').pop();
switch(ext){
case 'php':
this.appended
$(data).appendTo('body');
break;
case 'css':
$('<link/>')
.attr({
'rel':'stylesheet',
'href':url
}).appendTo('head');
break;
}
//Check if all files are included
i += 1;
if (i == len) {
$("body").trigger(name+"Ready");
}
});
});
}
};
var modules = {
themes : {
init : function(){
//Load dependencies
var deps = [
'/helpers/plupload/js/plupload.js,plupload.html5.js,plupload.flash.js'
];
if (!window.themesReady){
//Set themesReady to avoid double ajax requests
window.themesReady = true;
//Load dependencies
main.load('themes',deps);
$('body').on('themesReady',function(){
//Do whatever you need after it's ready
});
}
}
}
}
main.init();

Related

Execute Script tag using JS instead of PHP

I have a case in php, where I execute <script> tag of Adsense, if the userAgent is not BOT, but for some good reason I want to execute it using JS.
Helper Function:
function detectBottypes() {
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!empty($userAgent) and preg_match('~(bot|crawl|google|lighthouse|spider|feedparser|crawler|pinterest)~i', $userAgent)) {
return true;
}
return false;
}
in View:
#if( Request::is('photo/*') && detectBottypes()==false )
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" crossorigin="anonymous">
</script>
#endif
Above, if request is photo/* and not bot then it is rendered in view, but I want it to be rendered in either of cases but only executed for the specific case.
I have the case of JS
window.onload = function () {
var agent = navigator.userAgent.toLowerCase();
if (agent.indexOf('bot') != -1) {
// ******* Execute here ********
}
else {
}
}
Reason why I want: I cache the view file to skip the load on server, so if the page is first crawled by Bot(Google) it is cached without the above case of Adsense Script ( Ad is not loaded to Bot) but since it is cached if later it is viewed by real user, the cached version without Ads is shown which I do not want, so preferred to be with JS
You can dynamically load a script with something like:
window.onload = function () {
var agent = navigator.userAgent.toLowerCase();
if (agent.indexOf('bot') != -1) {
var scriptTag = document.createElement('script');
scriptTag.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
scriptTag.async = true;
scriptTag.type = 'text/javascript';
scriptTag.crossorigin = 'anonymous';
document.head.prepend(scriptTag);
} else {
}
}
This should cause the browser to download and run the script. However there's a broader question on your use of caching. It may be simpler if you cache two versions of the content and serve each one based on the UA, if that is an option.

load inserted script, making sure that libraries load first [duplicate]

I'm creating a jquery plugin and I want to verify an external script is loaded. This is for an internal web app and I can keep the script name/location consistent(mysscript.js). This is also an ajaxy plugin that can be called on many times on the page.
If I can verify the script is not loaded I'll load it using:
jQuery.getScript()
How can I verify the script is loaded because I don't want the same script loaded on the page more than once? Is this something that I shouldn't need to worry about due to caching of the script?
Update:
I may not have control over who uses this plugin in our organization and may not be able to enforce that the script is not already on the page with or without a specific ID, but the script name will always be in the same place with the same name. I'm hoping I can use the name of the script to verify it's actually loaded.
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter() functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.
Key points for me were
add an #id tag, so it's easy to find, and not duplicate
Use .onload() to wait until the script has finished loading before using it
mounted() {
// First check if the script already exists on the dom
// by searching for an id
let id = 'googleMaps'
if(document.getElementById(id) === null) {
let script = document.createElement('script')
script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
script.setAttribute('id', id)
document.body.appendChild(script)
// now wait for it to load...
script.onload = () => {
// script has loaded, you can now use it safely
alert('thank me later')
// ... do something with the newly loaded script
}
}
}
#jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:
function isScriptLoaded(src)
{
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
UPDATE July 2021:
The accepted solutions above have changed & improved much over time. The scope of my previous answer above was only to detect if the script was inserted in the document to load (and not whether the script has actually finished loading).
To detect if the script has already loaded, I use the following method (in general):
Create a common library function to dynamically load all scripts.
Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).
I use something like the following loadScript() function to load the script that uses callback functions to inform the calling modules if the script finished loading successfully.
I also use additional logic to retry when script loading fails (in case of temporary network issues).
Retry is done by removing the <script> tag from the body and adding it again.
If it still fails to load after configured number of retries, the <script> tag is removed from the body.
I have removed that logic from the following code for simplicity. It should be easy to add.
/**
* Mark/store the script as fully loaded in a global variable.
* #param src URL of the script
*/
function markScriptFullyLoaded(src) {
window.scriptLoadMap[src] = true;
}
/**
* Returns true if the script has been added to the page
* #param src URL of the script
*/
function isScriptAdded(src) {
return Boolean(document.querySelector('script[src="' + src + '"]'));
}
/**
* Returns true if the script has been fully loaded
* #param src URL of the script
*/
function isScriptFullyLoaded(src) {
return src in window.scriptLoadMap && window.scriptLoadMap[src];
}
/**
* Load a script.
* #param src URL of the script
* #param onLoadCallback Callback function when the script is fully loaded
* #param onLoadErrorCallback Callback function when the script fails to load
* #param retryCount How many times retry laoding the script? (Not implimented here. Logic goes into js.onerror function)
*/
function loadScript(src, onLoadCallback, onLoadErrorCallback, retryCount) {
if (!src) return;
// Check if the script is already loaded
if ( isScriptAdded(src) )
{
// If script already loaded successfully, trigger the callback function
if (isScriptFullyLoaded(src)) onLoadCallback();
console.warn("Script already loaded. Skipping: ", src);
return;
}
// Loading the script...
const js = document.createElement('script');
js.setAttribute("async", "");
js.src = src;
js.onload = () => {
markScriptFullyLoaded(src)
// Optional callback on script load
if (onLoadCallback) onLoadCallback();
};
js.onerror = () => {
// Remove the script node (to be able to try again later)
const js2 = document.querySelector('script[src="' + src +'"]');
js2.parentNode.removeChild(js2);
// Optional callback on script load failure
if (onLoadErrorCallback) onLoadErrorCallback();
};
document.head.appendChild(js);
}
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion #Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
Create the script tag with a specific ID and then check if that ID exists?
Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?
Edit: following feedback that a code example would be useful:
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
if(scripts.length){
for(var scriptIndex in scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):
(function(){
var desiredSource = 'https://sitename.com/js/script.js';
var scripts = document.getElementsByTagName('script');
var alreadyLoaded = false;
for(var scriptIndex in document.scripts) {
if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
alreadyLoaded = true;
}
}
if(!alreadyLoaded){
// Run your code in this block?
}
})();
Simply check if the global variable is available, if not check again. In order to prevent the maximum callstack being exceeded set a 100ms timeout on the check:
function check_script_loaded(glob_var) {
if(typeof(glob_var) !== 'undefined') {
// do your thing
} else {
setTimeout(function() {
check_script_loaded(glob_var)
}, 100)
}
}
Another way to check an external script is loaded or not, you can use data function of jquery and store a validation flag. Example as :
if(!$("body").data("google-map"))
{
console.log("no js");
$.getScript("https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initilize",function(){
$("body").data("google-map",true);
},function(){
alert("error while loading script");
});
}
}
else
{
console.log("js already loaded");
}
I think it's better to use window.addEventListener('error') to capture the script load error and try to load it again.
It's useful when we load scripts from a CDN server. If we can't load script from the CDN, we can load it from our server.
window.addEventListener('error', function(e) {
if (e.target.nodeName === 'SCRIPT') {
var scriptTag = document.createElement('script');
scriptTag.src = e.target.src.replace('https://static.cdn.com/', '/our-server/static/');
document.head.appendChild(scriptTag);
}
}, true);
Merging several answers from above into an easy to use function
function GetScriptIfNotLoaded(scriptLocationAndName)
{
var len = $('script[src*="' + scriptLocationAndName +'"]').length;
//script already loaded!
if (len > 0)
return;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
My idead is to listen the error log if there is an error on script loading.
const checkSegmentBlocked = (e) => {
if (e.target.nodeName === 'SCRIPT' && e.target.src.includes('analytics.min.js')) {
window.isSegmentBlocked = true;
e.target.removeEventListener(e.type, checkSegmentBlocked);
}
};
window.addEventListener('error', checkSegmentBlocked, true);
Some answers on this page are wrong. They check for the existence of the <script> tag - but that is not enough. That tells you that the tag was inserted into the DOM, not that the script is finished loading.
I assume from the question that there are two parts: the code that inserts the script, and the code that checks whether the script has loaded.
The code that dynamically inserts the script:
let tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'foo';
tag.src = 'https://cdn.example.com/foo.min.js';
tag.onload = () => tag.setAttribute('data-loaded', true); // magic sauce
document.body.appendChild(tag);
Some other code, that checks whether the script has loaded:
let script = document.getElementById('foo');
let isLoaded = script && script.getAttribute('data-loaded') === 'true';
console.log(isLoaded); // true
If the both of those things (inserting and checking) are in the same code block, then you could simplify the above:
tag.onload = () => console.log('loaded');
I found a quick tip before you start diving into code that might save a bit of time. Check devtools on the webpage and click on the network tab. The js scripts are shown if they are loaded as a 200 response from the server.

how to get loaded callback CSS files, JS files, font files with Jquery

I am making javascript for Page loader.
This is part of it.
$('img').each(function () {
var src = $(this).attr('src');
$('<img>').attr('src', src).on("load", function () {
alert("Loaded one of thme");
});
});
I can get callback from this, img files are OK.
But how to get callback of CSS files and JS files, especially font files?
regard.
/////////////////// add My resolve at 5/14
I resolved like this. Is this for just my case.
In HTML, Put link tags for fonts. Any where OK.
<link as="font" href="/fonts/font01.woff">
<link as="font" href="/fonts/font02.woff">
<img src="/img/img01.jpg">
<img src="/img/img02.jpg">
Next JS.
var fonts_length = $('link[as="font"]').length;
var resouce_num = $('img').length + fonts_length;
$('img').each(function () {
var src = $(this).attr('src');
$('<img>').attr('src', src).on("load", function () {
loadStatus++;
});
});
$('link[as="font"]').each(function () {
var href = $(this).attr('href');
$(document).load(href, function () {
loadStatus++;
});
});
And Compare loadStatus(loaded files count) and resouce_num(need load files count).
Is this correct using? I do not know, but working well, should be alright.
how do you think? If you have better way or found my mistake, tell me please.
And B--rian! please fix my english too!!
/////////////////// add Other nice way at 5/14
I found other one.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#Stylesheet_load_events
<script>
var myStylesheet = document.querySelector('#my-stylesheet');
myStylesheet.onload = function() {
// Do something interesting; the sheet has been loaded
}
myStylesheet.onerror = function() {
console.log("An error occurred loading the stylesheet!");
}
</script>
<link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet">
important Note:
Note: The load event fires once the stylesheet and all of its imported
content has been loaded and parsed, and immediately before the styles
start being applied to the content.
This way is much simple I thought.
But today I am so tired...later I will try.
/////////////////// add My trying at 5/15
I tried above one.But "onload" function is not working well.
It does not send callback after loaded... Chrome has problem? or My mistake?
Or this way is not nice for Page loader, I thought.
Cos, Even If that is working well, Can not check each loading of font files.
I think, Page loader should tell a temporary percentage of progress with a progress bar or something.
So, Now I am back to my sample script.
CSS files:
// create a nodeElement
var node = document.createElement('link');
node.rel = 'stylesheet';
node.href = url;
document.head.insertBefore(node, document.head.firstChild);
// try to set load callback
node.onload = function () {
CSSDone('onload listener');
// do your callback
}
if (node.addEventListener) {
node.addEventListener('load', function() {
CSSDone("DOM's load event");
// do your callback
}, false);
}
node.onreadystatechange = function() {
var state = node.readyState;
if (state === 'loaded' || state === 'complete') {
node.onreadystatechange = null;
CSSDone("onreadystatechange");
// do your callback
}
};
var cssnum = document.styleSheets.length;
var ti = setInterval(function() {
if (document.styleSheets.length > cssnum) {
CSSDone('listening to styleSheets.length change');
// do your callback
clearInterval(ti);
}
}, 10);
you can see this link for reference
JS files:
// create a nodeElement
var body = document.getElementsByTagName('body')[0];
var node = document.createElement('script');
node.setAttribute('type', 'text/javascript');
node.setAttribute('src', url);
body.appendChild(node);
// try to set load callback
if(node.onload){
node.onload = function() {
// do your callback
}
}else{
// for some not support onload
node.onreadystatechange = function() {
// do your callback
}
}
font files:
document.fonts.onloadingdone = function() {
// do your callback
}
how to check font files loaded can refer this link
emm,I am New contributor.if there are some wrong can reply me.thanks
If you are trying to print out the contents of a .css or .html file, you can do this with php:
<?php
$myfile = fopen("your_file", "r") or die("Unable to open file!");
echo fread($myfile,filesize("your_file"));
fclose($myfile);
?>

Loading javascript files in js files. Which is best way to check whether all files are loaded or not?

I have a array where i have specified the files i need to load in javascript before calling specific script. Lets call those particular lines of code as myscript.
I did as follows
var fileNamesArray = new Array();
fileNamesArray.push("abc.js");
fileNamesArray.push("pqr.js");
fileNamesArray.push("xyz.js");
fileNamesArray.push("klm.js");
var totalFiles = jQuery(fileNamesArray).length;
var tempCount = 0;
jQuery.each(fileNamesArray, function(key, value) {
jQuery.getScript(value, function() {
tempCount++;
});
});
to check whether all files are being loaded or not, i done following thing but doesn't seems to be effective
var refreshIntervalId = setInterval(function() {
if (tempCount == totalFiles) {
clearInterval(refreshIntervalId);
return;
}
}, 10);
i have implemented these in object oriented javascript as follows
function Loader() {
this.jQuery = null;
// check for specifically jQuery 1.8.2+, if not, load it
if (jQuery == undefined) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
} else {
var jQueryVersion = $.fn.jquery;
jQueryVersion = parseInt(jQueryVersion.split('.').join(""));
if (182 > jQueryVersion) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
}
}
}
Loader.prototype.LoadAllFile = function() {
//here i am loading all files
}
Loader.prototype.bindMap = function(options) {
this.LoadAllFile();
//execute the script after loading the files... which we called as myscript
}
i am loading more than 12-14 js files via ajax.
if you observe Loader.prototype.bindMap, i am loading all the files first and then executing the script.
But it seems that myscript the script start executing before all files being loaded.
what are the better ways to execute the script only after all js files are loaded.
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
Based on the documentation on Jquery.getScript , it is a shorthand for Jquery.ajax. By default this in async call. You might want to change it to do a synchronous call.
To set this property, you can refer to this
So instead of doing a setInterval, you can just loop in your array and do a Jquery.getScript.

How to use jQuery in Firefox Extension

I want to use jQuery inside a firefox extension,
I imported the library in the xul file like this:
<script type="application/x-javascript" src="chrome://myExtension/content/jquery.js"> </script>
but the $() function is not recognized in the xul file neither do the jQuery().
I googled about the problem and found some solutions but no one did work with me:
http://gluei.com/blog/view/using-jquery-inside-your-firefox-extension
http://forums.mozillazine.org/viewtopic.php?f=19&t=989465
I've also tried to pass the 'content.document' object(which refrences the 'document' object) as the context parameter to the jQuery function like this:
$('img',content.document);
but still not working,
does any one came across this problem before?
I use the following example.xul:
<?xml version="1.0"?>
<overlay id="example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<head></head>
<script type="application/x-javascript" src="jquery.js"></script>
<script type="application/x-javascript" src="example.js"></script>
</overlay>
And here is an example.js
(function() {
jQuery.noConflict();
$ = function(selector,context) {
return new jQuery.fn.init(selector,context||example.doc);
};
$.fn = $.prototype = jQuery.fn;
example = new function(){};
example.log = function() {
Firebug.Console.logFormatted(arguments,null,"log");
};
example.run = function(doc,aEvent) {
// Check for website
if (!doc.location.href.match(/^http:\/\/(.*\.)?stackoverflow\.com(\/.*)?$/i))
return;
// Check if already loaded
if (doc.getElementById("plugin-example")) return;
// Setup
this.win = aEvent.target.defaultView.wrappedJSObject;
this.doc = doc;
// Hello World
this.main = main = $('<div id="plugin-example">').appendTo(doc.body).html('Example Loaded!');
main.css({
background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8
});
main.html(main.html() + ' - jQuery <b>' + $.fn.jquery + '</b>');
};
// Bind Plugin
var delay = function(aEvent) {
var doc = aEvent.originalTarget; setTimeout(function() {
example.run(doc,aEvent);
}, 1);
};
var load = function() {
gBrowser.addEventListener("DOMContentLoaded", delay, true);
};
window.addEventListener("pageshow", load, false);
})();
The following solution makes it possibile to use jQuery in contentScriptFile
(Targetting 1.5 Addon-sdk)
In your main.js:
exports.main = function() {
var pageMod = require("page-mod");
pageMod.PageMod({
include: "*",
contentScriptWhen: 'end',
contentScriptFile: [data.url("jquery-1.7.1-min.js") , data.url("notifier.js") , data.url("message.js")],
onAttach: function onAttach(worker) {
//show the message
worker.postMessage("Hello World");
}
});
};
In your message.js :
self.on("message", function(message){
if(message !== "undefined"){
Notifier.info(message);
}
});
Some pitfalls you need to watchs out for:
The order of the contentScriptFile array. if message.js would be placed first: jQuery won't be reconized.
Do not place a http:// url in the data.url (this does not work)!
All your javascript files should be in the data folder. (only main.js should be in lib folder)
There is an excellent article in the mozillaZine forums that describes this step-by-step: http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087
I haven't tried it yet, though so I hesitate to duplicate the info here.
Turns out the current top-answer by #sunsean does not work as expected when it comes to handling multiple loads. The function should properly close over the document and avoid global state.
Also, you have to call jQuery.noConflict(true) to really avoid conflicts with other add-ons!
This is who I would write it (then again, I would avoid jquery (in add-ons) like the plague...).
First the overlay XUL
<?xml version="1.0"?>
<overlay id="test-addon-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="text/javascript" src="jquery.js"/>
<script type="text/javascript" src="overlay.js"/>
</overlay>
And then the overlay script:
// Use strict mode in particular to avoid implicitly var declarations
(function() {
"use strict";
// Main runner function for each content window.
// Similar to SDK page-mod, but without the security boundaries.
function run(window, document) {
// jquery setup. per https://stackoverflow.com/a/496970/484441
$ = function(selector,context) {
return new jq.fn.init(selector,context || document);
};
$.fn = $.prototype = jq.fn;
if (document.getElementById("my-example-addon-container")) {
return;
}
let main = $('<div id="my-example-addon-container">');
main.appendTo(document.body).text('Example Loaded!');
main.click(function() { //<--- added this function
main.text(document.location.href);
});
main.css({
background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8
});
};
const log = Components.utils.reportError.bind(Components.utils);
// Do not conflict with other add-ons using jquery.
const jq = jQuery.noConflict(true);
gBrowser.addEventListener("DOMContentLoaded", function load(evt) {
try {
// Call run with this == window ;)
let doc = evt.target.ownerDocument || evt.target;
if (!doc.location.href.startsWith("http")) {
// Do not even attempt to interact with non-http(s)? sites.
return;
}
run.call(doc.defaultView, doc.defaultView, doc);
}
catch (ex) {
log(ex);
}
}, true);
})();
Here is a complete add-on as a gist. Just drop in a copy of jquery and it should be good to go.
I think this is what Eric was saying, but you can load Javascript from the URL directly.
javascript:var%20s=document.createElement('script');s.setAttribute('src','http://YOURJAVASCRIPTFILE.js');document.getElementsByTagName('body')[0].appendChild(s);void(s);
Im assuming you want your extension to load JQuery so you can manipulate the page elements easily? My company's labs has something that does this using Javascript directly here: http://parkerfox.co.uk/labs/pixelperfect
It may be bad practice, but have you considered including it inline?
Instead of
$('img',content.document);
you can try
$('img',window.content.document);
In my case it works.

Categories

Resources