Can we load particular external java script files to particular div - javascript

I have two div in my html file and I am using two external javascript files.but the problem is when I am using both the js file together I am not getting the required functionality.so I want to restrict the use of js file to particular div
e.g: div1 should only use js1 file and div2 should only use js2 file so that no clash happens and I get the required functionality.
I am making a web app which is using lot number of widgets and these widgets are getting loaded from the database.there is one admin panel where a admin can add widgets.i am fetching all the widget's code from the database in a same page.so in future it may happen that after adding lot many widgets and there related js files they clashes and create problme.so i want to restrict there use to certain widget

Within a page (browsing context), there is only one JavaScript environment. To get the kind of isolation you're referring to, you'd have to create a separate browsing context by using an iframe or similar.

no what you are saying isnt possible. but what instead you can do is use diff scope for diff javascripts. If they are your own written js files
1. then simply change all the variables to be the properties of a global variables.
2. do not be dependent on the window variable
3. if your are using DOM manipulation using class names / tag names / attribute values which are common for both of the divs change them and also change the respective value on the div. So that you can access them sperately.
if they are one of the popular js libraries like jquery / _js / backbone
use the default no conflict option provided to load separate versions and then use them separately on the two separate divs.

I am not sure if you are using jquery or plain javascript.
if it is jquery then you can use jquery noconflict.
Create separate aliases to use jquery for div1 & div2
<script>
var div1Alias = $.noConflict();
var div2Alias = div1Alias.noConflict();
jQuery(document).ready(function(){
alert(div1Alias( "#div1" ).html());
alert(div2Alias( "#div2" ).html());
});
</script>
http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
How do I implement JQuery.noConflict() ?

Related

ajax load and conflicting css classes and IDs

I am building a simple single page application which contains some divs which I would like to fill with content from my wordpress website.
In order to do that, I am using ajax load and inserting the loaded content into my divs:
$('#my_div').load("https://example.com/page/")
The problem is that my application uses css from bootstrap which is different from the css from my wordpress website. However, because classes and IDs are identical, the css from the loaded page is replacing the css from my app.
How can I avoid that problem? I don't want to use iframes. Would it be possible to automatically rename every Class and ID name from the imported page so that it does not conflict?
I think the best way is to use get instead of load and replace the classes inside with replace if possible. In your case you can do like this:
$.get("https://example.com/page/", function(data) {
// replace classes
$("#my_div").replaceWith(data);
});

Can I insert HTML into a page via a file, and then interact with those DOM elements with JavaScript?

I'm building a Chrome Extension.
The extension injects some CSS and JavaScript when .html files on the users local drive are loaded in the browser (file:///).
My extension adds an extensive UI to the page that allows the user to modify and manipulate the original source code from their .html file.
The primary purpose of the extension is debugging and QAing HTML email newsletters. Here's just a few things that it does:
Checking links for the appropriate parameters.
Toggling images off and on to simulate popular email clients.
Displaying the source code side-by-side to show a desktop view and multiple mobile sized views.
A function that takes the original HTML and generates a plain text version.
A function that toggles <style> blocks off and on to simulate popular email clients ignoring them.
Email files are backed up via Dropbox and the Dropbox API is integrated to allow for quick sharing right from the email newsletter.
Until now I've been using javascript in my injected content script like this to create all of my menu items.
var debugOrb = document.createElement("div");
debugOrb.id = "borders-orb";
debugOrb.className = "borders-orb orb glyph";
debugOrb.addEventListener("click", toggleBorders, false);
orbsBottom.appendChild(debugOrb);
Here's an extended view of the code I've written to create all of these toggles/menu items: http://pastebin.com/LQTkNhpP
My problem is that now I'm going to be adding a LOT more clickable menu items like this. And it feels like if I do, it's going to get out of hand really quick. Especially since I'll be nesting a lot of divs to make the whole thing look organized and using JavaScript to create lots of text nodes too.
My first thought was what if I could just create my entire menu in regular HTML, then just inject that file into the page with the javascript in my content script. I'm barely intermediate level with JavaScript though. And as I understand it, if I did this, I'd lose my ability to use onclick handlers for all of these divs I'm creating.
Is there an efficient way to handle my goal that I'm not aware of?
Notes:
I'm not using any framework/plugins like React, Angular, or jQuery.
Once the html is added you can always get the element by id and then add an event listener to that element. You can have functions relate to the divs and then onload create the event listeners. element.addEventListener ('click', function);

Render Scripts-Section after scripts were loaded in ASP.NET Core PartialView

In an ASP.NET Core app, I've a dashboard with widgets. Every widget has its own PartialViews, so the full page is generated in the following way:
-Layout.cshtml
--Dashboard.cshtml
--- Widget1.cshtml
--- Widget2.cshtml
Following best practices according to fast page load times, JavaScript is loaded before the closing </body> tag in Layout.cshtml. After that, there is a section for custom JS, which I commonly use to initiate objects on page load. So this section looks like this:
<script asp-append-version="true" type="text/javascript" src="~/clientscript/page.min.js"></script>
#RenderSection("Js", required: false)
In my Views, which are using the Layout.cshtml as layout (in this example, its Dashboard.cshtml), I can define a section like
#section Js {
// Js Code here
}
which is rendered after the script tag containing all script files. So I can be sure, that all dependencies like jQuery or custom classes are avaliable here.
But I also need to do this in widgets like Widget1.cshtml for example. The problem is: I load the PartialView Widget1.cshtml in Dashboard.cshtml. In the documentation is written, that this is not possible:
If you declare a Razor section in a partial view, it will not be visible to its parent(s); it will be limited to the partial view.
But that's exactly what I need. Is there a way to work around this limitation? Shortly, the goal is to inject JavaScript from a PartialView to the LayoutView, with an regular View between them.
The only way I know is the usage of setInterval() with a low interval like 50ms, and check there if jQuery or some of my custom class is defined in a loop until they are. Its a JS solution yes. But it makes it possible to include the script-block directly in the PartialView without making usage of sections. It fits well when you depend on a single variable like jQuery.
But I need to wait for custom classes to get loaded. They're included after jQuery. So writing a generic function like waitForTypeLoaded(type, callback) is not possible. It would cause me to write always the raw setInterval() code, which seems not a smart solution for me.
Something I did to get my scripts to run after Jquery was done loading was in my Partial Views and View Components I used the "DOMContentLoaded" event to load all my jQuery js script after the page was done loading. That way I could defer the Load of jQuery and Still Have jQuery code on my pages.
<script>
window.addEventListener('DOMContentLoaded',
function() {
$('body')....
});
</script>
Your problem can be solved as mentioned in my answer to this post:
How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?
To sum up, you can create a pair of tag helpers, one that can be located in a partial view and just stores its content in a temporary dictionary, and the other that renders the content at the appropriate position (e.g. in the layout page). I use it extensively to render small dynamically created scripts as the final scripts of the body.
Hope it helps.
Honestly, I would make one step back and look at architecture once again if you have such dilemmas.
Why not add to required scripts which will be used on a couple of views/partial views to the main layout? In ASP.NET MVC you can use bundling mechanism (or you can write our own) - minify and bundle them with other required. It won't be heavy...
Your approach looks like unnecessary complicated.

Load external html file to div and use its js functions

I have some div:
<div id='dialog'></div>
Now I want to load into this div an external html file and use its js functions.
I know I can load it using jQuery.Load() and it works fine, the problem is that I want to use the html js functions.
The main problem is that I have several divs which I load this html file into them and I want that when I'm activating js function it will only work on the specific div.
Pass parameter to view that you are loading that will indicate container of the loaded view:
jQuery.Load(url, { containerId: 'dialog' })
I remember I had the problem back when jQuery1.4 was issued. In that version, .load() suddendly began stripping out the js when a target container was specified.
What I did at that time :
separate html and js in different files (let's say myhtml.html and myjs.js ), or views
have my js file act as a js module, with a public entry point function (say initContent) taking a jQuery element as a parameter
have an invisible link in myhtml.html, namely
after loading myhtml.html into my target div, search for $('a.dynamicJs') in my target div to extract js url, and entry point function from the href
if the js had not previously been loaded, dynamically load the js into the page trhough an ajax call
dynamically call the entry point function with the target div as parameter
This also worked with css.
It required some time to tweak it on all navigators (limited number of css sections on IE, different way to dynamically call a function), and I ended with much more code I expected in the first place. It also required a lot of refactoring of my html/js modules (but I must confess I ended having a code that was really cleaner)
I'm sure there are frameworks that handle this kind of situation way better by now. But this is what I came up with at that time.
Hope this will help

How can I have multiple document.observe(dom:loaded ...) functions inside one javascript file? (prototype)

Basically what I'm after is, following squashing all my JavaScript into one file (or a few files) how can I make a document.observe(dom:loaded({...})) function call for the right page?
So, say I have 5 pages in my website, and each one has a separate JS file. Inside each file is a load of page related functions, and a special function which sets up eventhandlers etc when the DOM has loaded. Obviously if all 5 pages include their own JS files then that's fine. But I want to compact all my JS into one page for versioning and efficiency reasons.
Therefore, in doing this, I would end up with 5 "dom:loaded" functions waiting to be setup. This won't do as the stuff inside these functions is page specific. So, my question is how can I do what I want to do without causing a whole bunch of DOM errors, and false eventhandler setup requests?
Ive considered namespaces and stuff like that but don't really know anything about it/them.
Btw, I'm using the Prototype lib. Oh, and my sites are considerably larger than 5 pages! :)
Thanks,
Lee
Some ideas:
inspect the dom to identify the page. For example, attach an attribute to the body element.
put a script tag in the page that sets a variable.
inspect the url.
when the load event fires, the event handler identifies the page and hands control off to the proper code.
I would give different IDs to the <body>s of the separate HTML files and test in the dom:loaded event the name of the <body> element using $$('body')[0].id.
I have opted to use a php regexp to capture the URI, then use this as the body ID. On my sites, where the page names are static, it means each page will have a unique ID.
I then include a JS file in the HEAD which contains a switch block inside which the appropriate code/functions are loaded. The switch block is inside the document.observe(dom:loaded...) function.
Works a treat!
Thank you again for your help.
I tend to always write my .js with no self activation (so much as possible)...
psuedo-code
namespace('mysite.section.init');
mysite.section.init.pageName = function(){
//stuff to run here...
};
in your home page, at the bottom, or via dom:loaded event simply run mysite.section.init.pageName();

Categories