make a jQuery plugin with plugins - javascript

I am trying to make a tinymce type editor. I want it to be extendable with plugins just like tinymce is. My question is how I could go about loading and using external javascript files in my plugin?

You could create a new script tag to pull in the javascript file:
YourEditor.loadPlugin = function(url) {
var scriptElement = document.createElement('script');
scriptElement.src = url;
document.body.appendChild(scriptElement);
};
If the loaded javascript was wrapped in a call to register itself with your editor:
YourEditor.registerPlugin("some-plugin", function(YourEditor) {
/* plugin code */
});
In your core code you would declare a function:
YourEditor.registerPlugin = function(name, loadFunction) {
loadFunction (this);
// fire an event (dummy syntax)
this.fire('pluginLoaded', name);
};
Then you could fire an event out of YourEditor to let the user of the editor know that the plugin 'some-plugin' has been loaded.
Registering the plugins works in a similar manner to jsonp in that it let's you load code from an arbitrary origin based on knowledge of a shared function. It passed a name and a function to call that will set up everything the plugin needs to operate.

Here is what I decided to do:
Use the jQuery.getScript() function. Didn't even know it existed.
So here's my code:
loadplugins: function() {
var self = this;
var settings = self.settings;
var plugins = settings.plugins.split(/[\s,]+/);
var thispath = settings.script_url;
$.each(plugins, function(i,e) {
// add .js to the plugin and the path before it
var thisPlugin = thispath + settings.plugin_dir + e + '.js'; // I'll change this to work with a script or directory
$.getScript(thisPlugin, function(data, textStatus, jqxhr) {
console.log(data, textStatus, jqxhr);
self.registerPlugin(data, function() {
});
});
});
return true;
},

Related

How to have my scripts interact with each other?

When my webpage has loaded it runs this script:
$(function() {
return $.ajax({
type: "get",
dataType: "json",
url: "/get_script",
success: function(data, status, xhr) {
return $("#myScript").html(data.myScript);
}
});
});
The script gets another script from my server (the data.myScript object). The new script that is added to my webpage looks like this:
<script>
initScript = function() {
return window.random_string = Math.random().toString(36).substring(7);
};
$(window).bind("popstate", 'hashchange', function() {
return initScript();
});
window.random_string = null;
initScript();
</script>
If the new script needs to make variables available for other scripts on the webpage I put them into a window.my_variable variable, but I'd like instead to be able to call e.g. MyScript.random_string.
I'd also like to be able to trigger the initScript function from other scripts. Like e.g. MyScript.initScript()
How do I achieve this?
Firstly I'd suggest using $.getScript to load your JS code assuming you cannot embed it directly in a <script> tag.
To solve your actual issue you just need to structure it in the manner you require. Simply create an object like var MyScript = {}; then place all the functions and variables as properties within that object, something like this:
$.getScript('/get_script', function() {
// put logic to run after the script has loaded here...
// note that you don't need your .html(data.myScript) any more
MyScript.initScript();
console.log(MyScript.random_string);
});
// in your external script:
var MyScript = {
initScript = function() {
this.random_string = Math.random().toString(36).substring(7);
},
random_string: null;
}

How to recognize that one js file loaded?

I try to display progress bar when page loading. I want change width of progress bar after js files loaded .At the final after load all documents set with of progress bar to 100% .Now I need to recognize js files loading with javascript.
Is this possible ? Please advice.
For internal js files loading recognition:
As functions and variables can be accessed from another file you can set the value of global progress variable and display it's value by calling the function
//on page or head js file
var progress = 0;
function displayProgress()
{
//show progress based on 'progress' variable
}
//file1.js
progress += 10;
displayProgress();
...
//file2.js
progress += 20;
displayProgress();
...
For external js files there is good article. The main idea is to periodically check existense of external functions (typeof fixpng =='function') and if it exist - stop checking and display progress.
Here's the JavaScript code to load the external library with a
callback passed in:
function loadExtScript(src, callback) { var s = document.createElement('script'); s.src = src; document.body.appendChild(s); // if loaded...call the callback }
Firefox allows you to listen for the onload event on the script
element:
s.onload = callback;
With Internet Explorer you can wait for a state change on the script
element:
s.onreadystatechange = function() { if ( this.readyState != "loaded"
) return; callback.call(); }
The problem comes with Safari - there's no event change for Safari, so
we can't tell when the script has loaded. This is the solution I came
up with (and this solution should also work with Opera):
function loadExtScript(src, test, callback) { var s =
document.createElement('script'); s.src = src;
document.body.appendChild(s);
var callbackTimer = setInterval(function() {
var call = false;
try {
call = test.call();
} catch (e) {}
if (call) {
clearInterval(callbackTimer);
callback.call();
} }, 100); }
The function takes a test as a parameter. Since you are the designer
of the app, you'll know what successful test is. Once this test is
true, it will execute the callback. A simple test could be to check
whether a function exists, for example:
loadExtScript('/fixpng.js', function() { return (typeof fixpng ==
'function'); }, myCallbackFunction);
If you know at least one defined namespace (almost all libraries and plugins have it: e.g. jQuery, jQuery.ui, jQuery.mobile, toastr, DataTable, etc.) or one global variable name introduced by the script files which are being loaded, then you can do this:
(function(undefined) {
var scriptFilesLoaded = false,
files = [],
timer = setInterval(function(){
try {
files = [
jQuery,
jQuery.mobile,
jQuery.ui,
someGlobalVariableName
];
if(files.indexOf(undefined)<0){
scriptFilesLoaded = true;
clearInterval(timer);
}
}
catch(e) {
console.warn('Preloader in action: Script files not loaded yet.');
}
},200);
})();
It doesn't matter if the script file is remote or local.

how to load precomplied template in backbone?

could you please tell me how to load precomplied templates .I googled it and find a solution .Now I don't know how to use this function.could you please tell me how to use this function ?
code:
http://goo.gl/ALfkzf
Backbone.Marionette.TemplateCache.prototype.loadTemplate = function (templateId, callback) {
var tmpId = templateId.replace("#", ""),
url = "/app/templates/" + tmpId + ".html";
$.get(url, function (templateHtml) {
compiledTemplate = Handlebars.compile($(templateHtml).html())
callback.call(this, compiledTemplate);
});
};
Backbone.Marionette.Renderer.renderTemplate = function (templateId, data) {
var renderer = $.Deferred();
Backbone.Marionette.TemplateCache.get(templateId, function(template){
var html = template(data);
renderer.resolve(html);
});
return renderer.promise();
};
I am trying to load html file which is inside the directory ? template/test.html
var ToolItemView = Backbone.Marionette.ItemView.extend({
template: 'template/test.html',
});
The code that you are trying to use, replaces default HTML mechanism in Marionette.
'template/test.html' will be translated to "/app/templates/template/test.html.html", which I guess is not what you want (Either change url generation, or template pointer)
Your Backbone code, does not assume, that "test.html" was precompiled on contrary compilation is happening on the client, following GET response, is this what you want?
Regarding Backbone override use, it should be called before you try to render your ToolItemView, so basically you can call this code anywhere before ToolItemView render.

Load Javascript into ajax loaded content

I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});

Verify External Script Is Loaded

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.

Categories